I’m trying to convert a C# DateTime variable to Unix time, ie, the number of seconds since Jan 1st, 1970. It looks like a DateTime is actually implemented as the number of ‘ticks’ since Jan 1st, 0001.
My current thought is to subtract Jan 1st, 1970 from my DateTime like this:
TimeSpan span= DateTime.Now.Subtract(new DateTime(1970,1,1,0,0,0));
return span.TotalSeconds;
Is there a better way?
That’s basically it. These are the methods I use to convert to and from Unix epoch time:
Update: As of .Net Core 2.1 and .Net Standard 2.1 a DateTime equal to the Unix Epoch can be obtained from the static
DateTime.UnixEpoch.