开发者

Javascript date to C# via Ajax

I have j开发者_运维百科avascript date object which gives me a date string in this format, "Wed Dec 16 00:00:00 UTC-0400 2009".

I pass this via Ajax to the server (ASP.NET c#)

How can I convert, "Wed Dec 16 00:00:00 UTC-0400 2009" to a C# DateTime object. DateTime.Parse fails.


You can use DateTime.ParseExact which allows you to specify a format string to be used for parsing:

DateTime dt = DateTime.ParseExact("Wed Dec 16 00:00:00 UTC-0400 2009",
                                  "ddd MMM d HH:mm:ss UTCzzzzz yyyy",
                                  CultureInfo.InvariantCulture);


The most reliable way would be to use milliseconds since the epoch. You can easily get this in JavaScript by calling Date.getTime(). Then, in C# you can convert it to a DateTime like this:

long msSinceEpoch = 1260402952906; // Value from Date.getTime() in JavaScript
return new DateTime(1970, 1, 1).AddTicks(msSinceEpoch * 10000);

You have to multiply by 10,000 to convert from milliseconds to "ticks", which are 100 nanoseconds.


This may not be possible in your case, but I really recommend updating the JS code to pass dates/times in ISO 8601 format. http://en.wikipedia.org/wiki/ISO_8601

ISO 8601 is not only the formal standard, it's also easy to use and prevents a lot of timezone hassle!

To get 8601 datetime strings in Javascript:

var d = new Date();
var iso_time = d.toISOString(); //"2014-05-06T18:49:16.029Z"

To read 8601 datetime strings in C#:

DateTime d = DateTime.Parse(json_string);


Just for posterity, to help future fellow Googlers, I'd like to expand on EMP's answer.

EMP's answer provides the time in UTC (if that's what you're looking for, use that).

To arrive at the client local time in C#:

In JavaScript:

        var now = new Date();
        var UTC = now.getTime();
        var localOffset = (-1) * now.getTimezoneOffset() * 60000;
        var currentTime = Math.round(new Date(UTC + localOffset).getTime()); 

In C#:

        DateTime currentTimeDotNet = new DateTime(1970, 1, 1).AddTicks(Convert.ToInt64(currentTime) * 10000);

Credit to this blog and EMP's answer, but took some trial and error on both ends to get it right, so just fyi for future folks.


To be honest I wouldn't try to parse that date string in C#, I'd personally try to create a more useful date structure from your javascript date object.

For instance you could use parse() in javascript which will return the ms representing the date object, which you can use DateTime.Parse() on to convert into a C# DateTime object.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜