日期(“2015-1-1”)与日期不同(2015-01-01) [英] Date('2015-1-1') outputs different from Date(2015-01-01)

查看:245
本文介绍了日期(“2015-1-1”)与日期不同(2015-01-01)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚发现,如果我使用 new Date('2015-1-1'),那么时间是没有时区效应的,但如果我使用 new Date('2015-01-01')时间在Node.js中有时区效应。

I just found that if I use new Date('2015-1-1'), the time is no timezone effect, but If I use new Date('2015-01-01') the time has timezone effect in Node.js.

我输出4 Date()

    console.log(new Date('2015-1-1'));
    console.log(new Date('2015-01-1'));
    console.log(new Date('2015-1-01'));
    console.log(new Date('2015-01-01'));

输出是

Thu Jan 01 2015 00:00:00 GMT+0800 (CST)
Thu Jan 01 2015 00:00:00 GMT+0800 (CST)
Thu Jan 01 2015 00:00:00 GMT+0800 (CST)
Thu Jan 01 2015 08:00:00 GMT+0800 (CST)

您可以看到最后一次是 08:00:00 因为我在+8时区。

you can see the last time is 08:00:00 because I'm in +8 timezone.

我认为输出取决于月份或日期数字的数字。当它是10,11或12时,输出总是 08:00:00

I think the output depends on the digit of the month or date number. When it's 10, 11 or 12 the output is always 08:00:00

我想知道为什么如果有更好的方法来处理这个,除了手动检查月份和日期数字的位?

I'm wondering why and if there is a better way to handle this except manually check the bit of month and date number?

推荐答案

直到并包括ECMA-262第3版,解析日期字符串完全取决于实现。使用ES5,没有时区的ISO 8601格式字符串将被解析为UTC,但解析任何其他类型的日期字符串仍然是依赖于实现的。

Up to and including ECMA-262 ed 3, parsing of date strings was entirely implementation dependent. With ES5, ISO 8601 format strings without a timezone were to be parsed as UTC, however parsing any other type of date string is still implementation dependent.

使用ECMAScript 2015,没有时区的字符串将被解析为本地(即基于系统设置的偏移量)。

With ECMAScript 2015, such strings without a timezone are to be parsed as local (i.e. with an offset based on system settings).

因此,您的Node.js实现似乎不能将前3个字符串识别为ISO 8601,因此根据将其视为UTC的其他内部逻辑进行解析。

So it would seem that your Node.js implementation does not recognise the first 3 strings as ISO 8601 and so parses them according to some other internal logic that treats them as UTC.

最后一个字符串被视为符合ISO 8601标准,因此被解析为本地。

The last string is seen as ISO 8601 compliant and so is parsed as local.

如果你想解析所有这样的字符串,如本地,你可以使用一个简单的函数,如:

If you wish to parse all such strings as local, you can use a simple function like:

/*  @param {string} s - date string in format yyyy-[m]m-[d]d
**  @returns {Date} - a Date object for the specified date in a
**  timezone based on system settings.
**  Assumes that the string is a valid date.
*/
function parseISOLocal (s) {
  var b = s.split(/\D/);
  return new Date(b[0], b[1]-1, b[2]);
}

document.write(parseISOLocal('2015-1-1'))

这篇关于日期(“2015-1-1”)与日期不同(2015-01-01)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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