How to Convert Unix Timestamp to DateTime in C#

By FoxLearn 11/27/2024 1:43:54 PM   708
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#

// convert timestamp to date c#
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).