Skip to content

Commit

Permalink
bypassing chrome intl timezone bug fix moment#517
Browse files Browse the repository at this point in the history
  • Loading branch information
bolasblack committed Sep 20, 2017
1 parent 15d1343 commit c632a68
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
23 changes: 22 additions & 1 deletion moment-timezone.js
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,7 @@
// use Intl API when available and returning valid time zone
try {
var intlName = Intl.DateTimeFormat().resolvedOptions().timeZone;
if (intlName){
if (isIntlNameCredible(intlName)){
var name = names[normalizeName(intlName)];
if (name) {
return name;
Expand Down Expand Up @@ -360,6 +360,27 @@
return zoneScores.length > 0 ? zoneScores[0].zone.name : undefined;
}

// for issue: https://github.com/moment/moment-timezone/issues/517
function isIntlNameCredible (intlName) {
if (!intlName) {
return false;
}

var zone = getZone(intlName),
browserOffset = new Date().getTimezoneOffset(),
i,
validOffset;
if (zone) {
for (i = 0; i < zone.offsets.length && !validOffset; i++) {
if (zone.offsets[i].offset === browserOffset) {
validOffset = zone.offsets[i].offset;
}
}
}

return !!validOffset;
}

function guess (ignoreCache) {
if (!cachedGuess || ignoreCache) {
cachedGuess = rebuildGuess();
Expand Down
16 changes: 15 additions & 1 deletion tests/moment-timezone/guess.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,11 @@ exports.guess = {

"When Intl is available, it is used" : function (test) {
mockIntlTimeZone('Europe/London');
mockTimezoneOffset(tz.zone('Europe/London'));
test.equal(tz.guess(true), 'Europe/London');

mockIntlTimeZone('America/New_York');
mockTimezoneOffset(tz.zone('America/New_York'));
test.equal(tz.guess(true), 'America/New_York');

mockIntlTimeZone('America/Some_Missing_Zone');
Expand All @@ -95,7 +97,7 @@ exports.guess = {
console.error = function (message) {
errors += message;
};

mockIntlTimeZone(undefined);
mockTimezoneOffset(tz.zone('Europe/London'));
test.equal(tz.guess(true), 'Europe/London');
Expand All @@ -115,5 +117,17 @@ exports.guess = {
test.ok(tz.guess(true), "Should have a guess for " + zone.name + ")");
}
test.done();
},

"check Intl.DateTimeFormat().resolvedOptions().timeZone is credible" : function (test) {
mockTimezoneOffset(tz.zone('Asia/Shanghai'))
mockIntlTimeZone('America/Chicago')
var guessedName = tz.guess(true)
test.equal(
tz.zone(guessedName).offset(Date.now()),
tz.zone('Asia/Shanghai').offset(Date.now()),
"Should have a guess for Asia/Shanghai)",
);
test.done();
}
};

0 comments on commit c632a68

Please sign in to comment.