C# DateTime to UNIX timestamps

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:

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, .NET Core, c#, General .NET and tagged , , , , . Bookmark the permalink.

5 Responses to C# DateTime to UNIX timestamps

  1. Russ says:

    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.

    Liked by 1 person

  2. briancaos says:

    Danm, you are absolutely right :) Thx mate, the method have been updated.

    Liked by 1 person

  3. Pingback: C# Calculate Week Number from DateTime | Brian Pedersen's Sitecore and .NET Blog

  4. Pingback: C# JWT Token Get Expiry Timestamp | Brian Pedersen's Sitecore and .NET Blog

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.