How can I convert a DateTime to the number of seconds since 1970?
Solution 1:
That's basically it. These are the methods I use to convert to and from Unix epoch time:
public static DateTime ConvertFromUnixTimestamp(double timestamp)
{
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
return origin.AddSeconds(timestamp);
}
public static double ConvertToUnixTimestamp(DateTime date)
{
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
TimeSpan diff = date.ToUniversalTime() - origin;
return Math.Floor(diff.TotalSeconds);
}
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
.
Solution 2:
If the rest of your system is OK with DateTimeOffset instead of DateTime, there's a really convenient feature:
long unixSeconds = DateTimeOffset.Now.ToUnixTimeSeconds();
Solution 3:
The only thing I see is that it's supposed to be since Midnight Jan 1, 1970 UTC
TimeSpan span= DateTime.Now.Subtract(new DateTime(1970,1,1,0,0,0, DateTimeKind.Utc));
return span.TotalSeconds;
Solution 4:
You probably want to use DateTime.UtcNow to avoid timezone issue
TimeSpan span= DateTime.UtcNow.Subtract(new DateTime(1970,1,1,0,0,0));
Solution 5:
I use year 2000 instead of Epoch Time in my calculus. Working with smaller numbers is easy to store and transport and is JSON friendly.
Year 2000 was at second 946684800 of epoch time.
Year 2000 was at second 63082281600 from 1-st of Jan 0001.
DateTime.UtcNow Ticks starts from 1-st of Jan 0001
Seconds from year 2000:
DateTime.UtcNow.Ticks/10000000-63082281600
Seconds from Unix Time:
DateTime.UtcNow.Ticks/10000000-946684800
For example year 2020 is:
var year2020 = (new DateTime()).AddYears(2019).Ticks; // Because DateTime starts already at year 1
637134336000000000 Ticks since 1-st of Jan 0001
63713433600 Seconds since 1-st of Jan 0001
1577836800 Seconds since Epoch Time
631152000 Seconds since year 2000
References:
Epoch Time converter: https://www.epochconverter.com
Year 1 converter: https://www.epochconverter.com/seconds-days-since-y0