Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bypassing chrome intl timezone bug fix #517 #529

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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 like Asia/Shanghai)"
);
test.done();
}
};