How to convert DateTime to seconds since 1970?

I am trying to convert a C # DateTime variable to Unix time, i.e. the number of seconds since January 1, 1970. It seems that DateTime is actually implemented as the number of ticks since January 1, 0001.

My current thought is to subtract January 1, 1970 from my DateTime as follows:

TimeSpan span= DateTime.Now.Subtract(new DateTime(1970,1,1,0,0,0)); return span.TotalSeconds; 

Is there a better way?

+92
c # datetime
Jul 28 '10 at 16:07
source share
7 answers

This is basically it. These are the methods that I use to convert to and from the Unix era:

 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); } 
+158
Jul 28 '10 at 16:09
source share

If the rest of your system is ok with DateTimeOffset instead of DateTime, there is a really handy function:

 long unixSeconds = DateTimeOffset.Now.ToUnixTimeSeconds(); 
+28
Jul 25 '16 at 0:46
source share

The only thing I see is that it should be from midnight on January 1, 1970 UTC

 TimeSpan span= DateTime.Now.Subtract(new DateTime(1970,1,1,0,0,0, DateTimeKind.Utc)); return span.TotalSeconds; 
+21
Jul 28 '10 at 16:12
source share

You probably want to use DateTime.UtcNow to avoid the time zone problem.

 TimeSpan span= DateTime.UtcNow.Subtract(new DateTime(1970,1,1,0,0,0)); 
+14
Jul 28 '10 at 16:13
source share

This approach would be good if the set time is in UTC or represents local time in an area that has never seen daylight saving time. DateTime difference procedures do not account for daylight saving time and, therefore, will consider midnight on June 1 as a multiple of 24 hours after midnight on January 1. I don’t know anything about Windows, which reports the historical daylight saving rules for the current locale, so I don’t think there is a good way to correctly handle any time until the last daylight saving time change rule.

+1
Jul 28 '10 at 17:21
source share

You can create startTime and endTime of DateTime and then do endTime.Subtract (startTime). Then print your span.Seconds.

I think this should work.

0
Jul 28 '10 at 16:13
source share

.NET Core has DateTime.UnixEpoch.Second

0
Dec 05 '18 at 23:42
source share



All Articles