How to Convert Unix Timestamp to DateTime in C#
By FoxLearn 3/21/2025 2:44:36 AM 1.78K
C# Get unix timestamp
To get the Unix timestamp (the number of seconds since January 1, 1970) in C#, you can use the DateTimeOffset
class.
For example:
// Get the current time as DateTimeOffset DateTimeOffset currentTime = DateTimeOffset.Now; // Unix epoch (January 1, 1970) // c# epoch to datetime DateTimeOffset unixEpoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero); // Get the Unix timestamp (seconds since the Unix epoch) long unixTimestamp = (long)(currentTime - unixEpoch).TotalSeconds; // c# timestamp Console.WriteLine($"Current Unix timestamp: {unixTimestamp}");
C# Convert epoch to datetime
In C#, you can convert an epoch timestamp (which is usually the number of seconds since January 1, 1970, also known as Unix epoch) to a DateTime
object using the DateTimeOffset
class or directly using DateTime
.
For example, Using DateTimeOffset
:
long epoch = 1615285000; // Example epoch time DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(epoch); DateTime dateTime = dateTimeOffset.DateTime; Console.WriteLine(dateTime); // Outputs the corresponding DateTime
For example, Using DateTime
If you prefer to use DateTime
instead of DateTimeOffset
, you can use this method:
long epoch = 1615285000; // Example epoch time DateTime dateTime = new DateTime(1970, 1, 1).AddSeconds(epoch); Console.WriteLine(dateTime); // Outputs the corresponding DateTime
Both of these methods will convert the Unix timestamp (epoch) into a DateTime
object that you can use for date/time manipulation in your application.
How to Convert Unix Timestamp to DateTime in C#?
For example, c# datetime from unix timestamp
// convert timestamp to date c# long unixTimestamp = 1626012000; // Replace with your Unix timestamp // c# 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 timestamp to datetime c# DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); // unix timestamp to date c# DateTime dateTime = epoch.AddSeconds(unixTimestamp);
We calculates the Unix timestamp based on the number of seconds since the Unix epoch (January 1, 1970).