How to Convert DateTime to Unix Timestamp in C#

By FoxLearn 7/11/2024 8:28:59 AM   96
In .NET, you can easily convert DateTime object back to a Unix timestamp.

Here's how to convert DateTime to Unix Timestamp in C#

To convert a DateTime object back to a Unix timestamp:

// Example DateTime
DateTime dateTime = DateTime.UtcNow; // Replace with your DateTime object

// Convert DateTime to Unix timestamp
long unixTimestamp = (long)(dateTime - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;

This calculates the number of seconds elapsed since the Unix epoch (1970-01-01T00:00:00Z) until the specified DateTime object.