File tree Expand file tree Collapse file tree 2 files changed +21
-2
lines changed Expand file tree Collapse file tree 2 files changed +21
-2
lines changed Original file line number Diff line number Diff line change @@ -20,8 +20,10 @@ export function formatDate(
2020
2121 switch ( format ) {
2222 case 'year-only' :
23- options . year = 'numeric' ;
24- break ;
23+ // If we're only using the year, ensure we output the correct UTC year and not
24+ // the local year. If the local timezone is used, we can get strange off-by-one
25+ // errors due to quirks of timezone handling for older years.
26+ return `${ date . getUTCFullYear ( ) } ` ;
2527 case 'short' :
2628 options . month = 'short' ;
2729 options . year = 'numeric' ;
Original file line number Diff line number Diff line change @@ -16,6 +16,23 @@ describe('formatDate', () => {
1616 expect ( formatDate ( testDate , 'long' ) ) . to . equal ( 'Dec 09, 2020' ) ;
1717 } ) ;
1818
19+ it ( 'returns year-only date when year-only DateFormat' , ( ) => {
20+ expect ( formatDate ( testDate , 'year-only' ) ) . to . equal ( '2020' ) ;
21+ } ) ;
22+
23+ it ( 'returns correct year for old "Jan 1 at midnight" dates and year-only DateFormat' , ( ) => {
24+ // Many standard timezones have a discontinuity in date parsing at some point during
25+ // the 19th or 20th century, corresponding to the creation of the timezone.
26+ // Dates prior to the discontinuity generally have a non-hour-aligned timezone offset
27+ // which can throw off the calculated year for dates which are close to a year boundary.
28+ // This is particularly problematic for "Jan 1 at midnight" dates, which are what we
29+ // receive from the search engine for date metadata that only specifies the year.
30+ // So we must ensure these older dates still output the correct year, not the prior one.
31+ expect ( formatDate ( new Date ( '1234-01-01T00:00:00Z' ) , 'year-only' ) ) . to . equal (
32+ '1234'
33+ ) ;
34+ } ) ;
35+
1936 it ( 'returns locale formatted date' , ( ) => {
2037 expect ( formatDate ( testDate , 'long' , 'de-DE' ) ) . to . equal ( '09. Dez. 2020' ) ;
2138 } ) ;
You can’t perform that action at this time.
0 commit comments