Share via


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

  • Anonymous
    March 20, 2004
    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
  • Anonymous
    March 22, 2004
    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?
  • Anonymous
    April 05, 2004
    The comment has been removed
  • Anonymous
    June 13, 2004
    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
  • Anonymous
    March 19, 2008
    PingBack from http://dev.ezoterik.info/2007/12/02/konvertaciya-vremeni/