2012-03-21

ASP.Net DateTime vs. Javascript Date

Lately I am spending quite some time with programming C# ASP.net applications. It is fun and far easier than I thought it would be. Of course, occasionally, one gets to the point where one wonders, 'WTF... Why doesn't this work!!!'

Yesterday, I got to that point, so as it was late I went to bed and started looking for a solution around the net today.

My problem was, that if you receive JSONified data from ASP the Date will be something like
 "/Date(139356000000+0200)/"

This is not necessarily a problem as one can guess what this string represents. The part before the '+' is the time in Milliseconds and the rest (including the '+') is the TimezoneOffzet as in '+/-hhmm', but there is no natural way to easily transform it (or at least, if it exists, it slipped my attention) to a Javascript Date-Object.

So in the end, the value above, that you get by JSON.parsing a ASP.net Webservice-Response, can be transformed by this Javascript-Function:
function DateTime2Date(input) {
    return new Date(parseInt(input.replace("/Date(""").replace(")/"""), 10))
}
And then of course, there is the next problem handling the Javascript Date when you want to send it back to the ASP.net WebService. The natural representation of the Javascript-Date when JSON.stringified looks like
"2012-03-06T23:00:00:000Z"
which again is a value that the ASP.net Webservice won't even consider to route through to the according Webservice Recipient. So in order to send (POST/PUT) this Date to the Webservice you will again have to modify the representation into a String using this Javascript Function:
function Date2DateTime(input) {
    var tzo = (input.getTimezoneOffset() / 60 * -100);
    tzo = (tzo < 0  ?    "" + ( tzo / -1000 >= 1 ? tzo : "0"+tzo )
                    :   "+" + ( tzo /  1000 >= 1 ? tzo : "0"+tzo ));
    return "\/Date(" + input.valueOf() + tzo + ")\/";
}
This method looks a bit odd, but if you know that 'getTimezoneOffset()' returns the offset in minutes rather than hours or in the '+/-hhmm' format and if you know that the value is returned is not the offset based on GMT but based on your local Timezone, it might make a bit more sense.

I hope this will help anyone who faces a similar situation.

No comments:

Post a Comment