Javascript 日期对象总是休息一天吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7556591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:43:04  来源:igfitidea点击:

Is the Javascript date object always one day off?

javascriptdate

提问by levi

In my Java Script app I have the date stored in a format like so:

在我的 Java Script 应用程序中,我以如下格式存储日期:

2011-09-24

Now when I try using the above value to create a new Date object (so I can retrieve the date in a different format), the date always comes back one day off. See below:

现在,当我尝试使用上述值创建一个新的 Date 对象(以便我可以以不同的格式检索日期)时,该日期总是在休息一天后返回。见下文:

var doo = new Date("2011-09-24");
console.log(doo);

logs:

日志:

Fri Sep 23 2011 20:00:00 GMT-0400 (Eastern Daylight Time)

采纳答案by zzzzBov

Notice that Eastern Daylight Time is -4 hoursand that the hours on the date you're getting back are 20.

请注意,东部夏令时间是-4 hours,您返回日期的小时数是20

20h + 4h = 24h

which is midnight of 2011-09-24.

这是 2011-09-24 的午夜。

You're getting the right date, you just never specified the correct time zone.

您得到了正确的日期,只是您从未指定正确的时区。

If you need to access the date values, you can use getUTCDate()or any of the other getUTC*()functions:

如果您需要访问日期值,您可以使用getUTCDate()任何其他getUTC*()功能

var d,
    days;
d = new Date('2011-09-24');
days = ['Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat'];
console.log(days[d.getUTCDay()]);

回答by SoEzPz

There are several crazythings that happen with a JS DATEobject that convert strings, for example consider the following date you provided

一些疯狂的事情,与JS发生日期对象,将字符串,例如考虑您提供以下日期

Note:The following examples may or may not be ONE DAY OFFdepending on YOURtimezone and current time.

注意:以下示例可能会或可能不会休息一天,具体取决于您的时区和当前时间。

new Date("2011-09-24"); // Year-Month-Day
// => Fri Sep 23 2011 17:00:00 GMT-0700 (MST) - ONE DAY OFF.

However, if we rearrange the string format to Month-Day-Year...

但是,如果我们将字符串格式重新排列为Month-Day-Year...

new Date("09-24-2011");
=> // Sat Sep 24 2011 00:00:00 GMT-0700 (MST) - CORRECT DATE.

Another strange one

另一个奇怪的

new Date("2011-09-24");
// => Fri Sep 23 2011 17:00:00 GMT-0700 (MST) - ONE DAY OFF AS BEFORE.

new Date("2011/09/24"); // change from "-" to "/".
=> // Sat Sep 24 2011 00:00:00 GMT-0700 (MST) - CORRECT DATE.

We could easily change hyphens in your date "2011-09-24"when making a new date

在创建新日期时,我们可以轻松更改日期“2011-09-24”中的连字符

new Date("2011-09-24".replace(/-/g, '\/')); // => "2011/09/24".
=> // Sat Sep 24 2011 00:00:00 GMT-0700 (MST) - CORRECT DATE.

What if we had a date string like "2011-09-24T00:00:00"

如果我们有一个像“2011-09-24T00:00:00”这样的日期字符串怎么办

new Date("2011-09-24T00:00:00");
// => Fri Sep 23 2011 17:00:00 GMT-0700 (MST) - ONE DAY OFF.

Now change hyphento forward slashas before; what happens?

现在像以前一样将连字符更改为正斜杠;发生什么了?

new Date("2011/09/24T00:00:00");
// => Invalid Date

I typically have to manage the date format 2011-09-24T00:00:00so this is what I do.

我通常必须管理日期格式2011-09-24T00:00:00所以这就是我所做的。

new Date("2011-09-24T00:00:00".replace(/-/g, '\/').replace(/T.+/, ''));
// => Sat Sep 24 2011 00:00:00 GMT-0700 (MST) - CORRECT DATE.

UPDATE

更新

If you provide separate arguments to the Date constructor you can get other useful outputs as described below

如果您为 Date 构造函数提供单独的参数,您可以获得其他有用的输出,如下所述

Note:arguments can be of type Number or String. I'll show examples with mixed values.

注意:参数可以是数字或字符串类型。我将展示具有混合值的示例。

Get the first month and day of a given year

获取给定年份的第一个月和第一天

new Date(2011, 0); // Normal behavior as months in this case are zero based.
=> // Sat Jan 01 2011 00:00:00 GMT-0700 (MST)

Get the last month and day of a year

获取一年的最后一个月和最后一天

new Date((2011 + 1), 0, 0); // The second zero roles back one day into the previous month's last day.
=> // Sat Dec 31 2011 00:00:00 GMT-0700 (MST)

Example of Number, String arguments. Note the month is March because zero based months again.

数字、字符串参数示例。请注意,月份是三月,因为再次以零为基础的月份。

new Date(2011, "02"); 
=> // Tue Mar 01 2011 00:00:00 GMT-0700 (MST)

If we do the same thing but with a day of zero, we get something different.

如果我们做同样的事情,但一天为零,我们会得到不同的东西。

new Date(2011, "02", 0); // again the zero roles back from March to the last day of February.
=> // Mon Feb 28 2011 00:00:00 GMT-0700 (MST)

Adding a day of zero to any year and month argument will get the last day of the previous month. If you continue with negative numbers you can continue rolling back another day

向任何年份和月份参数添加零日将获得上个月的最后一天。如果您继续使用负数,您可以继续回滚另一天

new Date(2011, "02", -1);
=> // Sun Feb 27 2011 00:00:00 GMT-0700 (MST)

回答by AaronLS

To normalize the date and eliminate the unwanted offset (tested here : https://jsfiddle.net/7xp1xL5m/):

将日期标准化并消除不需要的偏移(此处测试:https: //jsfiddle.net/7xp1xL5m/):

var doo = new Date("2011-09-24");
console.log(  new Date( doo.getTime() + Math.abs(doo.getTimezoneOffset()*60000) )  );
// Output: Sat Sep 24 2011 00:00:00 GMT-0400 (Eastern Daylight Time)

This also accomplishes the same and credit to @tpartee (tested here : https://jsfiddle.net/7xp1xL5m/1/):

这也实现了相同的功能并归功于@tpartee(此处测试:https: //jsfiddle.net/7xp1xL5m/1/ ):

var doo = new Date("2011-09-24");
console.log( new Date( doo.getTime() - doo.getTimezoneOffset() * -60000 )  );

回答by lincolnk

If you want to get hour 0 of some date in the local time zone, pass the individual date parts to the Dateconstructor.

如果要获取本地时区中某个日期的 0 小时,请将各个日期部分传递给Date构造函数。

new Date(2011,08,24); // month value is 0 based, others are 1 based.

回答by Kyle Shrader

Just want to add that apparently adding a space at the end of the string will use UTC for creation.

只想补充一点,显然在字符串末尾添加一个空格将使用 UTC 进行创建。

new Date("2016-07-06")
> Tue Jul 05 2016 17:00:00 GMT-0700 (Pacific Daylight Time)

new Date("2016-07-06 ")
> Wed Jul 06 2016 00:00:00 GMT-0700 (Pacific Daylight Time)

Edit: This is not a recommended solution, just an alternative answer. Please do not use this approach since it is very unclear what is happening. There are a number of ways someone could refactor this accidentally causing a bug.

编辑:这不是推荐的解决方案,只是一个替代答案。请不要使用这种方法,因为目前还不清楚发生了什么。有很多方法可以重构这个意外导致错误的方法。

回答by FishBasketGordo

I believe that it has to do with time-zone adjustment. The date you've created is in GMT and the default time is midnight, but your timezone is EDT, so it subtracts 4 hours. Try this to verify:

我认为这与时区调整有关。您创建的日期是 GMT,默认时间是午夜,但您的时区是 EDT,因此减去 4 小时。试试这个来验证:

var doo = new Date("2011-09-25 EDT");

回答by Aleks G

Your issue is specifically with time zone. Note part GMT-0400- that is you're 4 hours behind GMT. If you add 4 hours to the displayed date/time, you'll get exactly midnight 2011/09/24. Use toUTCString()method instead to get GMT string:

您的问题特别与时区有关。注意部分GMT-0400- 即您比格林威治标准时间晚 4 小时。如果您在显示的日期/时间上增加 4 小时,您将得到 2011/09/24 的午夜。使用toUTCString()方法来获取 GMT 字符串:

var doo = new Date("2011-09-24");
console.log(doo.toUTCString());

回答by Jie Zhang

This probably is not a good answer, but i just want to share my experience with this issue.

这可能不是一个好的答案,但我只想分享我在这个问题上的经验。

My app is globally use utc date with the format 'YYYY-MM-DD', while the datepicker plugin i use only accept js date, it's hard for me to consider both utc and js. So when i want to pass a 'YYYY-MM-DD' formatted date to my datepicker, i first convert it to 'MM/DD/YYYY' format using moment.js or whatever you like, and the date shows on datepicker is now correct. For your example

我的应用程序在全球范围内使用格式为 'YYYY-MM-DD' 的 utc 日期,而我使用的 datepicker 插件只接受 js 日期,我很难同时考虑 utc 和 js。因此,当我想将 'YYYY-MM-DD' 格式的日期传递给我的日期选择器时,我首先使用 moment.js 或您喜欢的任何格式将其转换为 'MM/DD/YYYY' 格式,日期选择器上显示的日期是现在正确的。对于你的例子

var d = new Date('2011-09-24'); // d will be 'Fri Sep 23 2011 20:00:00 GMT-0400 (EDT)' for my lacale
var d1 = new Date('09/24/2011'); // d1 will be 'Sat Sep 24 2011 00:00:00 GMT-0400 (EDT)' for my lacale

Apparently d1 is what i want. Hope this would be helpful for some people.

显然 d1 是我想要的。希望这对某些人有帮助。

回答by cmartin

This through me for a loop, +1 on zzzBov's answer. Here is a full conversion of a date that worked for me using the UTC methods:

这通过我进行了循环,对 zzzBov 的回答 +1。这是使用 UTC 方法对我有用的日期的完整转换:

//myMeeting.MeetingDate = '2015-01-30T00:00:00'

var myDate = new Date(myMeeting.MeetingDate);
//convert to JavaScript date format
//returns date of 'Thu Jan 29 2015 19:00:00 GMT-0500 (Eastern Standard Time)' <-- One Day Off!

myDate = new Date(myDate.getUTCFullYear(), myDate.getUTCMonth(), myDate.getUTCDate());
//returns date of 'Fri Jan 30 2015 00:00:00 GMT-0500 (Eastern Standard Time)' <-- Correct Date!

回答by pimvdb

It means 2011-09-24 00:00:00 GMT, and since you're at GMT -4, it will be 20:00the previous day.

这意味着2011-09-24 00:00:00 GMT,并且由于您在GMT -4,这将是20:00前一天。

Personally, I get 2011-09-24 02:00:00, because I'm living at GMT +2.

就个人而言,我明白了2011-09-24 02:00:00,因为我住在GMT +2