How can I convert a DateTime to the number of seconds since 1970?
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;
If the rest of your system is OK with DateTimeOffset instead of DateTime, there's a really convenient feature:
long unixSeconds = DateTimeOffset.Now.ToUnixTimeSeconds();
You probably want to use DateTime.UtcNow to avoid timezone issue
TimeSpan span= DateTime.UtcNow.Subtract(new DateTime(1970,1,1,0,0,0));
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
.