开发者

ASP.net c# Parse int as datetime

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 tran开发者_开发知识库sactionActualDate = 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.


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);


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)


Assuming this is unix time its the number of seconds, so

int unixtimestamp=int.Parse(str);
new DateTime(1970,1,1,0,0,0).AddSeconds(unixtimestamp);

like this fetcher guy said.

wiki says

Unix time, or POSIX time, is a system for describing points in time, defined as the number of seconds elapsed since midnight proleptic Coordinated Universal Time (UTC) of January 1, 1970, not counting leap seconds. I

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜