Dates in .net vs in javascript

2019-07-23 11:45发布

I have a ASP.NET WEB.API 4 and a Controller returning the following json:

{   date: "2013-03-14T00:00:00"   }

I parse it on the client (JavaScript):

date = new Date(json.date); // json.date being "2013-03-14T00:00:00"

Later I do a POST and in the body the date has changed format to

{   date: "2013-03-13T23:00:00.000Z"   }

My guess was that some time zone stuff has been added by JavaScript or the browser?

Because of DB storing dates as int (yyyymmdd) I do the following convertion:

public static int ToInt(DateTime date)
{
    return date.Year * 10000 + date.Month * 100 + date.Day;
}

The resulting int is then one day off :(

However if I do

date.ToLocalTime()

before calling the ToInt method, it looks fine.

Have I understood this correctly and is ToLocalTime() a sufficient solution or do I need to spend a day reading up on UTC dates in .NET and JavaScript?

Thanks!

2条回答
ら.Afraid
2楼-- · 2019-07-23 12:26
date = new Date(json.date); // json.date being "2013-03-14T00:00:00"

And what timezone is that json.date in? If there's no information about this, the JS Date constructor will assume it is the client's local timezone (and that is quite random). If you want it to be UTC, just add "Z" after your ISO-datestring:

date = new Date(json.date+"Z");

Also always use the [gs]etUTC(FullYear|Month|Date|…) methods then.

查看更多
The star\"
3楼-- · 2019-07-23 12:28

In my opinion you will get better result if your controller will return date in ZULU format. So before sending use: ToUniversalTime (http://msdn.microsoft.com/en-us/library/system.datetime.touniversaltime.aspx) Than the result also will be in ZULU format, so you don't have to convert it to LocalTime

查看更多
登录 后发表回答