-1

I have a date: yyyy-mm-dd that I am formatting using the International DateTimeFormat like this:

const formatter = new Intl.DateTimeFormat("en-US", { month: '2-digit', day: '2-digit', year: 'numeric', timeZone:'America/Denver'});

// GiVES SAME RESULTS AS ABOVE
//const formatter = new Intl.DateTimeFormat("en-US", { month: '2-digit', day: '2-digit', year: 'numeric'}); 
//const formatter = new Intl.DateTimeFormat("default" , { month: '2-digit', day: '2-digit', year: 'numeric'});

let date = "2020-03-19"
return formatter.format(Date.parse(date));

//returns 03/18/2020 which is one day behind

I've tried this with and without the timeZone attribute. How can I fix this?

3 Answers3

2

The ECMAScript Date Time String Format defines formats for both date-time forms as well as date-only forms. These are used by the Date.parse function and the Date constructor when a string is passed. Behavior for those functions is defined in the docs for the Date.parse function, which contain the following statement:

... When the UTC offset representation is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time.

Thus, when you call Date.parse('2020-03-19') the defined behavior is to treat that as UTC, not as local time. (This deviates from ISO 8601.)

To change this behavior, append a time string or a time+offset string.

For example, if you want to parse the time in the local computer's time zone:

Date.parse('2020-03-19T00:00:00.000')

Or, if you want to parse in a particular time zone and know the correct offset for the given timestamp in that time zone:

Date.parse('2020-03-19T00:00:00.000-05:00')

Often one doesn't know the offset, but does know the IANA time zone identifiers (such as 'America/Chicago'). Unfortunately, ECMAScript doesn't currently have the capability to parse in a named time zone yet. That capability will be possible if/when the TC39 Temporal proposal is adopted. Until then, you could use a library such as Luxon to perform such an action. For example:

luxon.DateTime.fromISO('2020-03-19', { zone: 'America/Chicago' }).toString()
//=> "2020-03-19T00:00:00.000-05:00"
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
0

Date.parse("2020-03-19") indicates 2020-03-19 00:00:00 GMT, so it will be 2020-03-18 for America/Denver, which will be 2020-03-18 17:00:00 America/Denver

const formatter1 = new Intl.DateTimeFormat("en-US", { month: '2-digit', day: '2-digit', year: 'numeric', timeZone:'America/Denver'});

const formatter2 = new Intl.DateTimeFormat("en-US", { month: '2-digit', day: '2-digit', year: 'numeric'}); 



let date = "2020-03-19"
console.log(formatter1.format(Date.parse(date)));
console.log(formatter2.format(Date.parse(date)));
wangdev87
  • 8,611
  • 3
  • 8
  • 31
-1

You have added time zone, because of that it convert date into that time zone and because of the zone it can be 1 day behind or next day.

Gaurav Patil
  • 1,162
  • 10
  • 20