How to get the unix timestamp in C#


I have had look around stackoverflow, and even looked at some of the suggested questions and none seem to answer, how do you get a unix timestamp in C#?

This question is tagged with c# timestamp unix-timestamp

~ Asked on 2013-07-13 17:33:25

The Best Answer is


You get a unix timestamp in C# by using DateTime.UtcNow and subtracting the epoch time of 1970-01-01.


Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

DateTime.UtcNow can be replaced with any DateTime object that you would like to get the unix timestamp for.

There is also a field, DateTime.UnixEpoch, which is very poorly documented by MSFT, but may be a substitute for new DateTime(1970, 1, 1)

~ Answered on 2013-07-13 17:33:25


As of .NET 4.6, there is DateTimeOffset.ToUnixTimeSeconds.

This is an instance method, so you are expected to call it on an instance of DateTimeOffset. You can also cast any instance of DateTime, though beware the timezone. To get the current timestamp:


To get the timestamp from a DateTime:

DateTime foo = DateTime.Now;
long unixTime = ((DateTimeOffset)foo).ToUnixTimeSeconds();

~ Answered on 2016-02-16 06:15:33

Most Viewed Questions: