Javascript日期字符串构造错误的日期 [英] Javascript Date string constructing wrong date

查看:90
本文介绍了Javascript日期字符串构造错误的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用一个字符串构造一个javascript日期对象,但它会保持错误的一天。它总是构建一天后来的一天。这是我的代码

  var date = new Date('2006-05-17'); 

我想要的日期是

  2006年5月17日星期三00:00:00 GMT-0700(PDT)

但是我得到

  Tue May 16 2006 17:00:00 GMT-0700(PDT)


解决方案

当您将日期作为字符串传递时,实现是浏览器特定的。大多数浏览器解释破折号意味着时间是UTC。如果您从UTC(您所做的)有负偏移量,它将显示在上一个当地的一天。



如果您希望本地日期,然后尝试使用斜杠,如下所示:

  var date = new Date('2006/05/17'); 

当然,如果您不必从字符串中解析,则可以传递各个数值参数相反,只需要知道,数字通过时,零是零。

  var date = new Date(2006,4,17 ); 

但是,如果您有字符串,并且希望将这些字符串解析为日期的一致性,使用 moment.js

  var m = moment('2006-05-17','YYYY-MM-DD'); 
m.format(); //或任何其他输出函数


Hi I am trying to construct a javascript date object with a string, but it keeps contructing the wrong day. It always constructs a day that is one day behind. Here is my code

var date = new Date('2006-05-17');

The date i want to get is

Wednesday May 17 2006 00:00:00 GMT-0700 (PDT)

But instead I get

Tue May 16 2006 17:00:00 GMT-0700 (PDT)

解决方案

When you pass dates as a string, the implementation is browser specific. Most browsers interpret the dashes to mean that the time is in UTC. If you have a negative offset from UTC (which you do), it will appear on the previous local day.

If you want local dates, then try using slashes instead, like this:

var date = new Date('2006/05/17');

Of course, if you don't have to parse from a string, you can pass individual numeric parameters instead, just be aware that months are zero-based when passed numerically.

var date = new Date(2006,4,17);

However, if you have strings, and you want consistency in how those strings are parsed into dates, then use moment.js.

var m = moment('2006-05-17','YYYY-MM-DD');
m.format(); // or any of the other output functions

这篇关于Javascript日期字符串构造错误的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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