new Date().toLocaleString not working on chrome

Viewed 13

I want to display UTC date '2020-01-14T17:43:37.000Z' in local timezone.

I am getting output like this :-

new Date('2020-01-14T17:43:37.000Z').toLocaleString(undefined, {dateStyle: "medium", timeStyle: 'long'});

Chrome

'Jan 14, 2020, 11:13:37 PM GMT+5:30'

FireFox

14-Jan-2020, 11:13:37 pm IST

How can i display Date in local timezone consistently accross all browsers?

1 Answers

Consistency is not guaranteed with toLocalString. All that's guaranteed is that the output is in a format that is reasonable to display to the user given the options specified.

That said, you can get the result you're looking for if you specify en-IN for the locale code, and Asia/Kolkata for the time zone.

const result = new Date('2020-01-14T17:43:37.000Z')
  .toLocaleString('en-IN', {
    dateStyle: "medium",
    timeStyle: 'long',
    timeZone: 'Asia/Kolkata'
  });
console.log(result);

You probably don't want to hardcode those into your application though. In your original code, undefined means to use the user's default locale, and the absence of timeZone means to use the user's default time zone. If the user happens to have en-IN and Asia/Kolkata, then they will see the same result as above.

Related