JavaScript 的 getDate 返回错误的日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2488313/
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-23 00:36:21  来源:igfitidea点击:

JavaScript's getDate returns wrong date

javascriptgetdate

提问by VahidN

The following script returns 20 instead of 21!

以下脚本返回 20 而不是 21!

var d = new Date("2010/03/21");
document.write(d.getDate());

What am I doing wrong? Is this a JavaScript bug?

我究竟做错了什么?这是一个 JavaScript 错误吗?

回答by CMS

The Date.parsemethod is implementation dependent (new Date(string)is equivalent to Date.parse(string)).

Date.parse方法依赖new Date(string)于实现(相当于Date.parse(string))。

While this format will be available on modern browsers, you cannot be 100% sure that the browser will interpret exactly your desired format.

虽然这种格式将在现代浏览器上可用,但您不能 100% 确定浏览器会准确地解释您想要的格式。

I would recommend you to manipulate your string, and use the Date constructor with the year, month and day arguments:

我建议您操作字符串,并使用带有年、月和日参数的 Date 构造函数:

// parse a date in yyyy-mm-dd format
function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
  return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}

回答by Paulo Buchsbaum

It's a daylight saving time issue, because Date()uses local time.

这是一个夏令时问题,因为Date()使用本地时间。

I live in Brazil and Oct-21-2012 is the start of daylight saving time in most of my country, so local dates at Oct-21-2012 between 0:0 and 1:0 doesn't exist in Brazil!

我住在巴西,2012 年 10 月 21 日是我所在国家/地区大部分地区夏令时的开始,因此巴西不存在 2012 年 10 月 21 日 0:0 和 1:0 之间的本地日期!

Some people comment here that it works. It happens because the right or wrong hour return depends on the local user country.

有些人在这里评论说它有效。发生这种情况是因为正确或错误的返回时间取决于当地的用户国家/地区。

See: http://www.timeanddate.com/news/time/brazil-dst-2012.html

见:http: //www.timeanddate.com/news/time/brazil-dst-2012.html

In Brazil, in 2012 Java thinks that DST starts at Oct-14 (actually it start at 1 week later)

在巴西,2012 年 Java 认为夏令时从 10 月 14 日开始(实际上是在 1 周后开始)

var dt = new Date(2012,9,14); 
alert(dt.getHours());

produces 1and

产生1

See: http://www.timeanddate.com/time/dst/2013.html

见:http: //www.timeanddate.com/time/dst/2013.html

The solution is use UTC (Coordinated Universal Time) time, because there is no Daylight Saving changes and you use a kind of abstract time. In most practical applications there is no problem.

解决方案是使用 UTC(协调世界时)时间,因为没有夏令时更改并且您使用一种抽象时间。在大多数实际应用中没有问题。

var dt = new Date( Date.UTC(2012, 9, 21, 8, 5, 12));
alert( (dt.getUTCMonth()+1) + '/' + dt.getUTCDate() + '/' + 
        dt.getUTCFullYear() + " " + dt.getUTCHours()+ ':' + 
        dt.getUTCMinutes() + ':' + dt.getUTCSeconds() );

it's easier if someone doesn't use hours, minutes and seconds, just place a dummy hour value greater or equal than 1, as I have shown above.

如果有人不使用小时、分钟和秒,则更容易,只需放置一个大于或等于 1 的虚拟小时值,如我上面所示。

回答by eyelidlessness

Any chance it's treating the string argument as UTC and the resulting Dateobject as local time, or vice versa? That could throw it off. Compare d.getDate()to d.getUTCDate().

是否有可能将字符串参数视为 UTC 并将结果Date对象视为本地时间,反之亦然?那可以扔掉它。比较d.getDate()d.getUTCDate()

回答by Chris

I also get a deviation of one day through getDate(), but I note that getUTCDate()returns the expected value. The problem was seen in FF 3.6.12, but the same code running on Chrome was fine.

我也得到了一天的偏差getDate(),但我注意到它getUTCDate()返回了预期值。该问题在 FF 3.6.12 中出现,但在 Chrome 上运行的相同代码没问题。

My debug code:

我的调试代码:

var date="2010-11-04";
alert(date);
var d = new Date(date)
alert(d.toDateString()+": "+ d.getDate()+" UTC "+d.getUTCDate());

This gave an output (FireFox):

这给出了一个输出(FireFox):

Wed Nov 03 2010: 3 UTC 4

2010 年 11 月 3 日星期三:3 UTC 4

Chrome is fine. So something is up somewhere - perhaps a bug, but more likely a timezone/UTC parameter issue. Reminds me of where PHP date()will return 23 hours in a day if the timezone changed that day etc. Buggered if I know what it is, though.

铬很好。所以某处出了点问题——可能是一个错误,但更可能是时区/UTC 参数问题。提醒我date()如果当天时区发生变化等,PHP将在一天中返回 23 小时的位置。不过,如果我知道它是什么,那就麻烦了。

回答by Steven Bala

It is the time zone which plays a major part here. The Date()function will add your time zone to the date which you are giving as an input. For example: I gave the input like this:

时区在这里起着重要作用。该Date()函数会将您的时区添加到您作为输入提供的日期中。例如:我给出了这样的输入:

alert(new Date("2018-09-15"));

The result for me is : Sat Sep 15 2018 05:30:00 GMT+0530 (India Standard Time)

我的结果是:Sat Sep 15 2018 05:30:00 GMT+0530(印度标准时间)

The timezone +05:30is added to my input's time( you can see in the above result..05:30:00 is being added to the date. Now what I'm telling is if you are in the time zone less than 0 [countries like brazil, mexico,chile,etc... having timezone less than 0] then it will add to your date input (eg: time zone is UTC?05:00. It will subtract -5:00 from the date given.

时区+05:30被添加到我输入的时间(你可以在上面的结果中看到..05:30:00 被添加到日期。现在我要说的是如果你在时区小于 0 [国家如巴西、墨西哥、智利等......时区小于 0] 然后它将添加到您的日期输入中(例如:时区是 UTC?05:00。它将从给定的日期中减去 -5:00。

VahidN, you got the result 20because you are in the time zone less than 0 (-1è :00`, etc...)

VahidN,您得到结果20是因为您所在的时区小于 0(-1è :00` 等...)

The solution is reset your time zone to 0. Like this:
Date("2010-03-21T00:00:00").

解决方案是将您的时区重置为 0。像这样:
日期(“2010-03-21T00:00:00”)。

回答by Jader Dias

I wrote the following code in my browser's address bar and the result was 21

我在浏览器的地址栏中写了以下代码,结果是 21

javascript:alert(new Date("2010/03/21").getDate())

There is no such thing as a Javascript bug, since there is many Javascript implementations, so you'll want to refer to a specific implementation.

没有 Javascript 错误这样的东西,因为有很多 Javascript 实现,所以你需要参考一个特定的实现。

The implementation I tested was Chrome 4.1.249. What's yours?

我测试的实现是 Chrome 4.1.249。你的是啥呢?

回答by Leniel Maccaferri

I tested this code in Firefox 3.6 and IE 8:

我在 Firefox 3.6 和 IE 8 中测试了这段代码:

<script type="text/javascript">

var d = new Date("2010/03/21");
document.write(d.getDate());

</script> 

It's showing the right date: 21

它显示了正确的日期:21

For more information, look at: JavaScript Date Object

有关更多信息,请查看:JavaScript 日期对象

You can also read about JavaScript Compatibility considerationsat Wikipedia.

您还可以在 Wikipedia 上阅读JavaScript 兼容性注意事项

回答by kennebec

I get the same date (21) in firfox,safari,chrome,opera and IE, whether I use the string "2010/03/21" or the integer date arguments (2010,2,21).

无论我使用字符串“2010/03/21”还是整数日期参数(2010,2,21),我在 firfox、safari、chrome、opera 和 IE 中都得到相同的日期(21)。

I am using a windows machine and new versions of the browsers-

我正在使用 Windows 机器和新版本的浏览器-

you can test to see if your client parses a different date from the string, which is the only place I see for a problem.

您可以测试以查看您的客户端是否从字符串解析了不同的日期,这是我发现问题的唯一地方。

if(new Date("2010/03/21")- new Date(2010,2,21)){
alert(new Date("2010/03/21"));
} 

回答by NilColor

http://jsbin.com/aqoki3/edit- here with code you posted I get 21. So its not JS bug. Maybe its bug in your browser implementation (of JS).
So to correctly init your date var use new Date(year, month, date [, hour, minute, second, millisecond ])(https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Date). This way you will be sure that day is 21 becouse you implicitly set it to 21.

http://jsbin.com/aqoki3/edit- 这里有你发布的代码,我得到了21。所以它不是JS错误。也许它在您的浏览器实现(JS)中的错误。
因此,要正确初始化您的日期变量使用new Date(year, month, date [, hour, minute, second, millisecond ])https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Date)。这样你就可以确定那天是 21,因为你隐式地将它设置为 21。

回答by CG_DEV

Make sure the number month you are using is -1, If you are looking at June, you need to do (6-1) for the month, when create

确保您使用的数字月份为 -1,如果您正在查看六月,则需要为该月份执行 (6-1),创建时

   var date_obj = new Date(y,(m-1),d);