How to Convert DateTime to Unix Timestamp in C#

By FoxLearn 12/12/2024 1:21:06 AM   643
In .NET, you can easily convert DateTime object back to a Unix timestamp.

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

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

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