How to get the unix timestamp in C#

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:

DateTimeOffset.Now.ToUnixTimeSeconds()

To get the timestamp from a DateTime:

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

Leave a Comment