日期在.net vs在javascript [英] Dates in .net vs in javascript

查看:82
本文介绍了日期在.net vs在javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET WEB.API 4和一个Controller返回以下json:

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

我在客户端(JavaScript)上解析: / p>

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

稍后我做POST和身体的日期已经更改格式为

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

我的猜测是JavaScript或浏览器添加了一些时区的东西? >

由于DB存储日期为int(yyyymmdd),我做以下转换:

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

然后,生成的int就有一天:(



但是,如果我执行

  date.ToLocalTime()

在调用ToInt方法之前,看起来很好。



正确的是ToLocalTime()是一个足够的解决方案,还是需要花费一天时间阅读.NET和JavaScript中的UTC日期?



谢谢!

解决方案


  date = new Date(json.date); // json。日期为2013-03-14T00:00:00


什么时区是 json.date ?如果没有关于这个的信息, JS Date 构造函数将假定它是客户端的本地时区(这是相当随机的)如果你想要UTC,只需添加在您的ISO-datestring之后,Z

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

还总是使用 [gs] etUTC(FullYear | Month | Date | ...)方法然后。


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!

解决方案

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.

这篇关于日期在.net vs在javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆