Trivia: How to convert a JSON2.org DateTime string to C# DateTime
Asp.Net MVC 2 Futures doesn't seem to handle JSON DateTime well (including double and decimal values). As such, I setup all inputs as string, used Data Validation, and things worked pretty well.
However, I have this JSON2.js date from Firefox 3.6:
"/Date(1288296203190)/"
How do I turn this in to a valid date in C#?
var a = new DateTime(1288296203190);
That doesn't give the right date (1/2/0001 11:47:09 AM) instead of Thu Oct 28 2010 16:03:23 GMT-0400 (Eastern Daylight Time). It's probably because a 32 bit integer is only 10 digits. However,开发者_如何学运维 this fails too:
var a = Int64.Parse("1288296203190");
var b = new DateTime(a);
b's value is 1/2/0001 11:47:09 AM.
What did it do? Wrap? Is this some kind of time travel "signed bit" issue?
The issue is the difference in epoch. Looks like the JSON2.js date you have uses the unix epoch (January 1, 1970) measured in ms. From the System.DateTime(long ticks) documenttion:
expects A date and time expressed in the number of 100-nanosecond intervals that have elapsed since January 1, 0001 at 00:00:00.000 in the Gregorian calendar.
Something like this should get you what you want.
var unixEpoch = DateTime(1970, 1, 1);
var ticksSinceEpoch = 1288296203190 * 10000;
var time = new DateTime(unixEpoch.Ticks + ticksSinceEpoch);
And there is even better way (which also takes 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)
var jsonDate = "/Date(1288296203190+0530)/";
var strSec = jsonDate.Substring(6, 13);
var strTimeZone = jsonDate.Substring(19, 5);
sec = double.Parse(strSec);
var timeZoneHr = double.Parse(strTimeZone);
var timeZoneMin = timeZoneHr % 100;
timeZoneHr = Math.Ceiling(timeZoneHr / 100);
var date = new System.DateTime(1970, 1, 1, 0, 0, 0, 0)
.AddMilliseconds(sec)
.AddHours(timeZoneHr)
.AddMinutes(timeZoneMin);
I parsed the string myself. Its working fine for me. Anybody have other optimized way, please let me know.
This question is basically the same as this one: ASP.net c# Parse int as datetime.
And I think the accepted answer there is better than @matheeeny's answer (although matheeeny explained well the problem of OP's original solution).
I'll copy here LukeH's accepted answer:
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);
精彩评论