Search code examples
c#timestampunix-timestamp

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#?


Solution

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

    e.g.

    Int32 unixTimestamp = (int)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)