Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

date.toLocaleDateString(locale,{timeZone:'Asia/Kolkata'}) not working in ie 11

I am trying to convert date and time with timezone and locale but, it is not working in IE11. It is working in chrome, firefox, and edge.

Minimally complete verifiable example:

function getLocalTime(date){
    var timeZone = "Asia/Kolkata";
    var utcDate =  new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));
    var dateAndTime = utcDate.toLocaleDateString("en",{timeZone:timeZone})+" "+ utcDate.toLocaleTimeString("en",{timeZone:timeZone}).replace(/:\d+ /, ' ');;
    return dateAndTime;
}

console.log(getLocalTime(Date());

Error in IE11:

SCRIPT5118: Option value 'ASIA/KOLKATA' for 'timeZone' is outside of valid range. Expected: ['UTC']

Note: I don't want to use any third party js.

like image 415
Passionate developer Avatar asked Jun 07 '17 02:06

Passionate developer


1 Answers

timeZone documentation on MDN says that support for timezone strings is optional, except for "UTC":

The only value implementations must recognize is "UTC"; the default is the runtime's default time zone. Implementations may also recognize the time zone names of the IANA time zone database, such as "Asia/Shanghai", "Asia/Kolkata", "America/New_York".

Relevant portions of the ECMAScript spec confirm this (hat tip to @mkaatman):

[[timeZone]] is either the String value "UTC" or undefined.

A conforming implementation is permitted to accept additional values, and then have implementation-defined behaviour instead of throwing a RangeError, for [...t]he options property timeZone in the DateTimeFormat constructor, provided that the additional acceptable input values are case-insensitive matches of Zone or Link identifiers in the IANA time zone database and are canonicalized to Zone identifiers in the casing used in the database for the timeZone property of the object returned by DateTimeFormat.resolvedOptions, except that "Etc/GMT" shall be canonicalized to "UTC".

Microsoft's documentation states they started supporting localeDateString in IE11:

Starting in Internet Explorer 11, toLocaleDateString uses Intl.DateTimeFormat internally to format the date, which adds support for the locales and options parameters.

...but based on your error message their support is for the minimal "'UTC' or undefined" version. The timezone database is here for what it's worth, but it looks like you'll need to find a different way to handle this (probably involving getTimezoneOffset() rather than named timezones.)

like image 84
Daniel Beck Avatar answered Oct 20 '22 17:10

Daniel Beck