Amazon.com Widgets

Seconds since the Unix epoch in C#

A question about how to get the “C style representation” out of a DateTime came over an internal alias recently.  Turns out the person needed the number of seconds since the Unix epoch.  Not too bad to do with the DateTime class…   

 

     TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));

     int timestamp  = (int) t.TotalSeconds;

     Console.WriteLine (timestamp);

 

But notice I did use the UtcNow property to ensure that the timestamp is the same regardless of what timezone this code is being run it.  If you are doing something timestamp related and you are NOT using UtcNow, chances are you have bug.  

 

 

 

Published 20 March 04 04:57 by BradA
Filed under:

Comments

# phil said on March 21, 2004 7:48 AM:
Ahh ... but the thing you might have to deal with more often is not "seconds" but miliseconds as people/programs have often serialized the 1970-epoch'd times with a precision of milliseconds to a double with no precision. In addition to time epoch issues, the nanosecond precision in .NET compounds the problem of trying to get date interoperablity ...

In VB.NET:

' Number of 100 nanosecond units from 1/1/1601 to 1/1/1970.
Const WIN32_FILETIME_EPOCH_BIAS As Int64 = 116444736000000000

Public Shared Function DateTimeToDouble(ByVal InDate As Date) As Double
DateTimeToDouble = CDbl((InDate.ToFileTimeUtc() - _
WIN32_FILETIME_EPOCH_BIAS) / 10000)
End Function

Public Shared Function DateTimeToDouble(ByVal InDate As Date) As Double
DateTimeToDouble = CDbl((InDate.ToFileTimeUtc() - _
WIN32_FILETIME_EPOCH_BIAS) / 10000)
End Function
# theCoach said on March 22, 2004 11:22 AM:
Sorry, if this is obvious, but I was poking around and did not see a date formatter for XSD formats - is there one in the framework?
# webfootguy said on April 5, 2004 11:15 AM:
Shouldn't the first line of the code look like this:

TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1).ToLocalTime());

Since the first DateTime has been converted to UTC, I think the second one should too.

I also agree the milliseconds/nanosecond problem crops up often.
# mitesh v mehta said on June 14, 2004 3:39 AM:
Please find the code below to convert currentdatetime to epoch time in c#

public long GetEpochTime()
{
DateTime dtCurTime = DateTime.Now;
DateTime dtEpochStartTime = Convert.ToDateTime("1/1/1970 8:00:00 AM");
TimeSpan ts = dtCurTime.Subtract(dtEpochStartTime);

long epochtime;
epochtime = ((((((ts.Days * 24) + ts.Hours) * 60) + ts.Minutes) * 60) + ts.Seconds);
return epochtime;
}


With Best Regards,

Mitesh Mehta
miteshvmehta@gmail.com
# ?????????????? ???????????????????????? » ?????????? ?????????? » ?????????????????????? ?????????????? said on March 19, 2008 8:36 AM:

PingBack from http://dev.ezoterik.info/2007/12/02/konvertaciya-vremeni/

New Comments to this post are disabled

Search

This Blog

Syndication

Page view tracker