Axel
Axel

Reputation: 5111

Moment Timezone returns correct timezone but with wrong spelling

I am using MomentJS Timezone. However, when I do moment.tz.guess(), it returns my timezone with wrong spelling.

const timezone = moment.tz.guess();
console.log(timezone); //returns Asia/Katmandu instead of Asia/Kathmandu

Yes, I could've just edited the js file and corrected the spelling but I'm afraid it's same for other countries too. Since I will be unaware of it, this might degrade the user experience!

Is this behavior expected or is there any way to fix it?

SEE THIS: Correct Timezone List [Moment] [Javascript] [PHP] [Internationalization API]

Upvotes: 8

Views: 1856

Answers (2)

Ullas Hunka
Ullas Hunka

Reputation: 2211

I am using moment 2.2.22 and 0.5.17 data, here is the result I found.

var timezones = moment.tz.names();
console.log(moment.tz.guess());
for (var i = 0; i < timezones.length; i++) {
  var node = document.createElement("LI");
  var textnode = document.createTextNode(timezones[i]);
  node.appendChild(textnode);
  document.getElementById("mm").appendChild(node);

}
#mm span {
  width: 100%;
}
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="http://momentjs.com/downloads/moment-timezone-with-data.min.js"></script>
<ul id='mm'></ul>

My result showed that there are two names coming for same timezone (Kathmandu and Katmandu), which has written like Asia/Kathmandu|Asia/Katmandu (one updated second obsolete). After researching slight a bit I found this is because obsolete timezone and chrome behaviour this issue will not occur on Firefox or any other browser.

This issue is also not going to be resolved by developers as this doesn't create any problem. This is a known Chrome behaviour that leads to Moment making an incorrect guess. The Moment development team is uninterested in developing a workaround. More info can be found here.

So I would suggest you use string and format it according to your need and suggested on the previous answer.

Note

Please test the example in other browsers as well.

Upvotes: 1

Durga
Durga

Reputation: 15604

See this post why results differ. If you are getting result Asia/Katmandu return value as Asia/Kathmandu.

//for kathmandu, it returns Asia/Katmandu(chrome)
//returns Asia/Kathmandu (firfox);
var timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
if(timeZone === 'Asia/Katmandu'){
  timeZone = 'Asia/Kathmandu';
}
console.log(timeZone);

MomentJs DEMO

var timeZone = moment.tz.guess();
if(timeZone === 'Asia/Katmandu'){
  timeZone = 'Asia/Kathmandu';
}
console.log(timeZone);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.21/moment-timezone-with-data.js"></script>

Upvotes: 0

Related Questions