ASP.net c# Parse int as datetime

11,422

Solution 1

var dt = new DateTime(1970, 1, 1).AddMilliseconds(1286294501433);

You might also need to specify the DateTimeKind explicitly, depending on your exact requirements:

var dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
             .AddMilliseconds(1286294501433);

Solution 2

And to simplify it even further and also take your local timezone into account:

Just create this integer number extension -

  public static class currency_helpers {
    public static DateTime UNIXTimeToDateTime(this int unix_time) {
      return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(unix_time).ToLocalTime();
    }
  }

And then call it wherever like this:

var unix_time = 1336489253;    
var date_time = unix_time.UNIXTimeToDateTime();

The value of date_time is:

5/8/2012 10:00:53 AM

(via: http://www.codeproject.com/Articles/10081/UNIX-timestamp-to-System-DateTime?msg=2494329#xx2494329xx)

Share:
11,422

Related videos on Youtube

Tom Gullen
Author by

Tom Gullen

Me Web developer. Website http://www.scirra.com

Updated on May 05, 2022

Comments

  • Tom Gullen
    Tom Gullen almost 2 years

    Given a time:

    1286294501433

    Which represents milliseconds passed since 1970, how do we convert this to a DateTime data type? EG:

    transactionTime = "1286294501433";
    UInt64 intTransTime = UInt64.Parse(transactionTime);
    DateTime transactionActualDate = DateTime.Parse(intTransTime.ToString());
    

    Throws:

    String was not recognized as a valid DateTime.

    Please note all times passed into this function are guaranteed to be after 1970.