2017-08-04 68 views
2

为什么如果我选择1848年以下的年份,这种格式的结果是May 10Intl.DateTimeFormat给出了1847年或以下的奇怪结果

我有一种感觉,这可能是关于时区?如果是这样,我怎么能避免这种情况,因为我将从ISO日期字符串(没有时间)这样创建一个日期对象:YYYY-MM-DD

(测试铬59)上述

const workingDate = Intl.DateTimeFormat('en-GB').format(new Date('Fri May 11 1848 01:00:00 GMT+0100 (BST)')); 
 
const notWorkingDate = Intl.DateTimeFormat('en-GB').format(new Date('Fri May 11 1847 01:00:00 GMT+0100 (BST)')); 
 

 
console.log(workingDate); 
 
console.log(notWorkingDate);

日期字符串是从例如new Date('1847-05-11')(我在BST时区)

+0

请参阅[*为什么Date.parse会给出错误的结果?*](https://stackoverflow.com/questions/2587345/why-do-date-parse-give-incorrect-results) – RobG

回答

2

这个测试是在Chrome 53

由我添加了一些选项来DateTimeFormat检查的日期等字段:

options = { 
    year: 'numeric', month: 'numeric', day: 'numeric', 
    hour: 'numeric', minute: 'numeric', second: 'numeric', 
    hour12: false, timeZoneName: 'long' 
}; 
var workingDate = Intl.DateTimeFormat('en-GB', options).format(new Date('Fri May 11 1848 01:00:00 GMT+0100 (BST)')); 
var notWorkingDate = Intl.DateTimeFormat('en-GB', options).format(new Date('Fri May 11 1847 01:00:00 GMT+0100 (BST)')); 

其结果是:

workingDate: 10/05/1848, 20:53:32 GMT-03:06:28 
notWorkingDate: 10/05/1847, 20:53:32 GMT-03:06:28 

大多数地方根本没有1900(实际上,每个国家在不同的年通过的话)之前,标准化的基于UTC-偏移,所以要在1900年以前,你总会得到那些奇怪的结果实际上,作为Matt explained in the comments,UTC在1972年实施,在此之前,大多数区域被定义为与GMT的偏移量。无论如何,对于非常古老的日期,特别是在1900年以前,您可能会预计像上述这样的偏移量。

在这种情况下,它获得了我系统的默认时区(America/Sao_Paulo)的相应偏移量:在1914年之前它是-03:06:28

在伦敦(这我假设它的默认时区),before 1847-12-01 the offset was -00:01:15(由经/纬度计算,详见再次Matt's comment),之后又改为+00:00(这就是为什么它工作的日期在1848年)。

我做了一个测试设置时区以Europe/London

options = { 
    year: 'numeric', month: 'numeric', day: 'numeric', 
    hour: 'numeric', minute: 'numeric', second: 'numeric', 
    hour12: false, timeZoneName: 'long', timeZone: 'Europe/London' 
}; 
var workingDate = Intl.DateTimeFormat('en-GB', options).format(new Date('Fri May 11 1848 01:00:00 GMT+0100 (BST)')); 
var notWorkingDate = Intl.DateTimeFormat('en-GB', options).format(new Date('Fri May 11 1847 01:00:00 GMT+0100 (BST)')); 

结果是:

1848年11月5日,00:00:00 GMT
10/05/1847,23:58:45 GMT-00:01:15

这证实在12月/ 1847年之前,日期有不同的偏移量。


人去修补的方式,是考虑日期UTC:

options = { 
    timeZone: 'UTC' 
}; 
var workingDate = Intl.DateTimeFormat('en-GB', options).format(new Date('Fri May 11 1848 01:00:00 GMT+0100 (BST)')); 
var notWorkingDate = Intl.DateTimeFormat('en-GB', options).format(new Date('Fri May 11 1847 01:00:00 GMT+0100 (BST)')); 

值将是:

1848年11月5日
11月5日/ 1847

+1

伟大的答案!谢谢。我不会问你为什么使用Chrome 53;) –

+0

不客气,很高兴帮助!好吧,我也很惊讶,Chrome没有更新... – 2017-08-04 18:36:23

+2

很好的答案,但只是为了纠正几点:1)UTC直到1972年才实现。在此之前,大多数(但不是全部)时区是定义为来自GMT的偏移量。 2)'-00:01:15'偏移描述[本地平均时间](https://en.wikipedia.org/wiki/Local_mean_time),而不是标准时间。换句话说,过去政府表示他们比格林威治标准时间或世界标准时间晚1分钟。相反,它是按纬度/经度计算的。请注意,可以将[tzdb条目](https://github.com/eggert/tz/blob/2017b/europe#L464)标记为LMT。干杯! –