C# Tip Article
Unix timestamp conversion built in .NET
In my previous post How to get unix timestamp in C#, I explained how to use unix timestamp in C#. From .NET 4.6, unix timestamp conversion feature is now built-in. This feature supports unix timestamp represented by seconds or milliseconds. Here is the example for unix timestamp conversion.
// 1) Convert seconds unix timestamp to DateTimeOffset type (UTC): long timestamp1 = 1629565973L; var dt1 = DateTimeOffset.FromUnixTimeSeconds(timestamp1); //8/21/2021 5:12:53 PM GMT // 2) Convert milliseconds unix timestamp to DateTimeOffset type (UTC): long timestamp2 = 1629565973000L; var dt2 = DateTimeOffset.FromUnixTimeMilliseconds(timestamp2); //8/21/2021 5:12:53 PM GMT // 3) Convert current UTC time to unix timestamp in seconds long secs = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); // 1629566869 // 4) Convert current UTC time to unix timestamp in milliseconds long ms = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); // 1629566869086