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.  


 


 


 

Comments (5)

  1. phil says:

    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

  2. theCoach says:

    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?

  3. webfootguy says:

    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.

  4. mitesh v mehta says:

    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