Although the UNIX timestamp (also known as the EPOCH time or the POSIX time) probably does not make sense to you, it is still widely used. After all, who cares how many seconds have elapsed since Jan 1st 1970, right? Well, lets not worry about that, instead lets see how we can convert a standard C# DateTime into a UNIX timestamp.
EDIT 2022-07-01: There was an issue in my extension method where I converted the current time instead of the parameter value. Thanks to Russ for the pointer.
The trick is to convert the DateTime into a DateTimeOffset, and convert it from there to the UNIX timestamp number.
Now, there is 2 versions of the UNIX timestamp, one just displaying the number of seconds and another one where the milliseconds are added:
// Get the offset from current time in UTC time
DateTimeOffset dto = new DateTimeOffset(DateTime.UtcNow);
// Get the unix timestamp in seconds
string unixTime = dto.ToUnixTimeSeconds().ToString();
// Get the unix timestamp in seconds, and add the milliseconds
string unixTimeMilliSeconds = dto.ToUnixTimeMilliseconds().ToString();
The code above will have the following results:
- Current UTC time: 2/24/2022 10:37:13 AM
- UNIX timestamp: 1645699033
- UNIX timestamp, including milliseconds: 1645699033012
If you wish, you can wrap this in an Extension method on your DateTime class:
public static class DateTimeExtensions
{
// Convert datetime to UNIX time
public static string ToUnixTime(this DateTime dateTime)
{
DateTimeOffset dto = new DateTimeOffset(dateTime.ToUniversalTime());
return dto.ToUnixTimeSeconds().ToString();
}
// Convert datetime to UNIX time including miliseconds
public static string ToUnixTimeMilliSeconds(this DateTime dateTime)
{
DateTimeOffset dto = new DateTimeOffset(dateTime.ToUniversalTime());
return dto.ToUnixTimeMilliseconds().ToString();
}
}
MORE TO READ:
- UNIX Time from Wikipedia
- EPOCH from Wikipedia
- EPOCH Converter – Converts UNIX timestamps
- .NET DateTime to JSON UNIX JavaScript datetime from briancaos
Hi, I believe there is an error in your ToUnixTime methods. Both of these methods take a parameter that is never used in the function. I believe your intent was to use this when creating the DateTimeOffset dto, rather than DateTime.UtcNow.
LikeLiked by 1 person
Danm, you are absolutely right :) Thx mate, the method have been updated.
LikeLiked by 1 person
Here’s my grain of salt: https://currentmillis.com/standard/specification/client-centric-time/
LikeLike
Pingback: C# Calculate Week Number from DateTime | Brian Pedersen's Sitecore and .NET Blog
Pingback: C# JWT Token Get Expiry Timestamp | Brian Pedersen's Sitecore and .NET Blog