2017-08-04 70 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。乾杯! –