How to Convert Unix Timestamp to DateTime in C#

By FoxLearn 7/11/2024 8:29:36 AM   25
In .NET, you can easily convert Unix timestamps to DateTime objects by using DateTimeOffset.FromUnixTimeSeconds method.

How to Convert Unix Timestamp to DateTime in C#

// Example Unix timestamp
long unixTimestamp = 1626012000; // Replace with your Unix timestamp

// Convert Unix timestamp to DateTime
DateTime dateTime = DateTimeOffset.FromUnixTimeSeconds(unixTimestamp).DateTime;

This method uses DateTimeOffset.FromUnixTimeSeconds to convert a Unix timestamp to a DateTime object.

For old version .NET you can use DateTime.FromFileTimeUtc

// Example Unix timestamp
long unixTimestamp = 1626012000; // Replace with your Unix timestamp

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

We calculates the Unix timestamp based on the number of seconds since the Unix epoch (January 1, 1970).