How to convert timestamp to date in C#

By FoxLearn 11/16/2024 2:26:23 AM   116
In C#, to convert a timestamp to a DateTime object, you can use the DateTimeOffset or DateTime class.

A timestamp in C# represents time as the number of seconds (or milliseconds) since the Unix epoch (January 1, 1970). Converting a timestamp to a date is often required for proper representation, as it provides a human-readable format of the time.

This conversion is important for accurately displaying information about files, folders, or packages. It ensures that both date and time are available, helping to provide precise details and proper context for any time-based data.

How to Convert Timestamp to Date in C#?

If you have a Unix timestamp, you can convert it to a DateTime as follows:

For example:

// convert timestamp to date c#
// Example Unix timestamp (milliseconds since Unix epoch)
long unixTimestamp = 1413761632;
// Convert to DateTime
var dateTime = new System.DateTime(1980, 1, 1, 0, 0, 0, 0);
dateTime = dateTime.AddSeconds(unixTimestamp);
System.Console.WriteLine($"{dateTime.ToShortDateString()} {dateTime.ToShortTimeString()}");//10/18/2024 11:33 PM

This program demonstrates how to convert a Unix timestamp into a human-readable date format. Specifically, it shows how the Unix timestamp corresponds to the date and time of October 18, 2024, at 11:33 PM in the output.

If the timestamp is in milliseconds, you can use FromUnixTimeMilliseconds method:

For example:

// Example Unix timestamp (milliseconds since Unix epoch)
long unixTimestamp = 1617845980123;
// Convert to DateTime
DateTime dateTime = DateTimeOffset.FromUnixTimeMilliseconds(unixTimestamp).DateTime; //4/8/2021 1:39:40 AM
Console.WriteLine(dateTime);

This program demonstrates the conversion of a Unix timestamp to a DateTime object in C#. The output shows the accurate calculation of the converted DateTime based on the given Unix timestamp.