开发者

Javascript ASP.net date format without timezone info - timezone offsets

I have a client side JavaScript that generates a date in JavaScript( new Date(2007,5,1)).

I need this date passed through to a hidden field that the code behind can access.

My issue is that when the hidden field is convert开发者_Python百科ed into a DotNet datetime, the time is incorrect. This is because the JavaScript is including timezone info from the client browser.

DotNet is then using this info to recalculate the time based on the difference between the server time and the client time.

What i need from the JavaScript is just the year, month and day.

I don't want to pass through 3 int values to my code behind as this will be a major change to the whole app.

What is the best way for me to accomplish this?

If i can set a UTC time with no timezone info I think that might work.

Any help is appreciated.


demo

If I understood it correctly,

you need .toDateString()

var date = new Date(2007,5,1);

document.write(date);
document.write("<br><br>versus<br><br>");
document.write(date.toDateString());

prints

Fri Jun 01 2007 00:00:00 GMT+0800 (Taipei Standard Time)

versus

Fri Jun 01 2007


You can use DateTimeOffset.ParseExact to parse a string to a DateTimeOffset value using the format you specify:

        string dateString = "Fri Jun 01 2007 00:00:00 GMT+08:00";
        DateTimeOffset date = DateTimeOffset.ParseExact(dateString, "ddd MMM dd yyyy hh:mm:ss 'GMT'zzz", CultureInfo.InvariantCulture);

You have to put GMT in quotes otherwise M will be interpreted as a format character.

Unfortunatelly, it is not possible to ignore part of the string value. If your string includes the name of the timezone you have to split it first and get the part without the description

        string dateString = "Fri Jun 01 2007 00:00:00 GMT+08:00 (Taipei Standard Time)";
        var parts=dateString.Split('(');
        string datePart = parts[0].TrimEnd();
        var date=DateTimeOffset.ParseExact(datePart,"ddd MMM dd yyyy hh:mm:ss 'GMT'zzz",CultureInfo.InvariantCulture);


You can build up a string from the javascript Date object you have created - it has getDate(), getMonth() and getFullYear() methods that you can use to build up the exact string you want in the hidden field.


I would recommend to use a format specification in C# when you get the values in the code behind file. Let me explain what I mean - The date time format for the Date(...) in JavaScript is as follows

"Tue Jun 1 11:12:15 UTC+0530 2010"

which in C# would translate to the following format string - "ddd MMM d hh:mm:ss UTCzzz yyyy"

with this format string use the DateTime.ParseExact(string <Hidden Field Value>, format, provider) to get the correct value for the datetime in C#.

Use provider as System.Globalization.CultureInfo.InvariantCulture.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜