Replace date-string parsing in CPTimeZone with Intl API

* Update abbreviationForDate and _abbreviationForNameAndDate to read the short time zone name directly from Intl.DateTimeFormat(...).formatToParts(). This replaces regular expression parsing of date strings.

 * Update knownTimeZoneNames to use Intl.supportedValuesOf('timeZone') to retrieve the complete IANA time zone set. The method falls back to the legacy 48-city list if Intl is unavailable.

* Replace duplicate regular expression logic in testInitWithNameRespectsDaylightSaving with a direct Intl call.

* Add pinning tests for the recently corrected offsets and the unchanged MSD value.

* Add a feature-detected test for the knownTimeZoneNames upgrade.

* Add two disabled tests to document unresolved gaps: non-English localizedName outputs and ambiguous reverse offset lookups.

* The full IANA-identity redesign as a separate task. Abbreviation-keyed lookups, colliding offsets, and English-only localizedName limitations remain unresolved in this interim fix.
This commit is contained in:
David Richardson committed 2026-08-28 14:19:46 -06:00
1 parent f3a04f23f8
commit c39f03823a
2 files changed
+122 -45

No files matched your search

+44 -40
View File
@@ -47,30 +47,26 @@ var abbreviationDictionary,
function abbreviationForDate(date)
{
// Strategy 1: Parse date.toString() as it's more reliable than toLocaleString.
// Format is usually: "Day Mon dd yyyy hh:mm:ss GMT+XXXX (Time Zone Name)"
var dateString = date.toString();
// Strategy 1: ask Intl directly for the short time zone name (e.g. "PDT") of
// the runtime's local zone, which correctly reflects DST for this date.
// Replaces the previous date.toString() parenthesis-scraping and
// long-name-to-acronym regex guessing, which broke for locales and
// engines that don't format Date#toString the way that logic assumed.
try {
var parts = new Intl.DateTimeFormat('en-US', { timeZoneName: 'short' }).formatToParts(date),
tzPart = parts.filter(function (p) { return p.type === 'timeZoneName'; })[0];
// Check for a long name within parentheses, e.g., (Pacific Daylight Time)
var longNameMatch = dateString.match(/\(([^)]+)\)/);
if (longNameMatch) {
var timeZoneComponent = longNameMatch[1];
// If the component is already a known abbreviation (e.g., "EST"), return it.
if ([abbreviationDictionary objectForKey:timeZoneComponent]) {
return timeZoneComponent;
}
// If it's a long name (e.g., "Eastern Daylight Time"), create an acronym.
if (timeZoneComponent.indexOf(' ') > -1) {
var generatedAbbr = timeZoneComponent.split(' ').map(function(word) { return word[0]; }).join('');
if ([abbreviationDictionary objectForKey:generatedAbbr]) {
return generatedAbbr;
}
}
if (tzPart && [abbreviationDictionary objectForKey:tzPart.value])
return tzPart.value;
} catch (e) {
// Intl API not supported, or it failed. Fall through to strategy 2.
}
// Strategy 2: If string parsing fails (e.g., for "GMT-04:00"), use the modern and reliable Intl API.
// Strategy 2: if the short name Intl returned isn't one of our known
// abbreviations (e.g. it returned "GMT-04:00" for a zone with no common
// three/four-letter abbreviation), resolve the runtime's IANA zone and
// pick whichever known abbreviation for that zone matches the date's
// current UTC offset.
try {
var ianaName = new Intl.DateTimeFormat().resolvedOptions().timeZone;
var currentOffset = -date.getTimezoneOffset(); // in minutes
@@ -108,28 +104,18 @@ function abbreviationForDate(date)
function _abbreviationForNameAndDate(tzName, date)
{
// This is a helper function based on the existing `abbreviationForDate`.
// It determines the abbreviation for a given IANA name based on the provided date,
// which allows it to respect daylight saving time.
// Determines the abbreviation for a given IANA name based on the provided
// date, which allows it to respect daylight saving time. Reads the short
// time zone name directly from Intl.formatToParts, rather than parsing
// a long name out of toLocaleString's locale-formatted output.
try {
var options = {
timeZone: tzName,
timeZoneName: 'long'
};
// The 'en-US' locale provides a predictable format for parsing.
var dateString = date.toLocaleString('en-US', options);
var parts = new Intl.DateTimeFormat('en-US', { timeZone: tzName, timeZoneName: 'short' }).formatToParts(date),
tzPart = parts.filter(function (p) { return p.type === 'timeZoneName'; })[0];
// This regex is copied from the global 'abbreviationForDate' function.
// It strips the date and time, leaving the long time zone name.
var longTZName = dateString.replace(/^([0]?\d|[1][0-2])\/((?:[0]?|[1-2])\d|[3][0-1])\/([2][01]|[1][6-9])\d{2}(,?\s*([0]?\d|[1][0-2])(\:[0-5]\d){1,2})*\s*([aApP][mM]{0,2})?\s*/, "");
// Create the abbreviation from the long name (e.g., "Pacific Daylight Time" -> "PDT")
var abbreviation = longTZName.split(" ").map(function(l) { return l[0]}).join("");
return abbreviation;
return tzPart ? tzPart.value : nil;
} catch (e) {
// The tzName might be invalid for toLocaleString, which throws a RangeError.
// In this case, we can't determine the abbreviation.
// The tzName might be invalid for Intl.DateTimeFormat, which throws a
// RangeError. In this case, we can't determine the abbreviation.
return nil;
}
}
@@ -205,6 +191,24 @@ function _abbreviationForNameAndDate(tzName, date)
@"Asia/Jakarta"
];
// Prefer the runtime's own IANA database, when it exposes one, over the
// hardcoded 48-city list above: it's the full current set, not a snapshot
// that will silently drift the way the hand-maintained tables above have.
if (typeof Intl !== "undefined" && typeof Intl.supportedValuesOf === "function")
{
try
{
var supportedZones = Intl.supportedValuesOf("timeZone");
if (supportedZones && supportedZones.length > 0)
knownTimeZoneNames = supportedZones;
}
catch (e)
{
// Fall through, keep the hardcoded list above.
}
}
abbreviationDictionary = @{
@"ADT" : @"America/Halifax",
@"AKDT" : @"America/Juneau",
+78 -5
View File
@@ -357,11 +357,14 @@
var expectedAbbreviationLA;
try {
// This logic mimics the _abbreviationForNameAndDate helper function in CPTimeZone.j
var options = { timeZone: laTimeZoneName, timeZoneName: 'long' };
var dateString = (new Date()).toLocaleString('en-US', options);
var longTZName = dateString.replace(/^([0]?\d|[1][0-2])\/((?:[0]?|[1-2])\d|[3][0-1])\/([2][01]|[1][6-9])\d{2}(,?\s*([0]?\d|[1][0-2])(\:[0-5]\d){1,2})*\s*([aApP][mM]{0,2})?\s*/, "");
expectedAbbreviationLA = longTZName.split(" ").map(function(l) { return l[0]}).join("");
// This logic mirrors the _abbreviationForNameAndDate helper in
// CPTimeZone.j: read the short time zone name directly from Intl,
// as an independent check that CPTimeZone's own use of the same
// API returns the same thing, not a duplicate of an algorithm.
var options = { timeZone: laTimeZoneName, timeZoneName: 'short' };
var parts = new Intl.DateTimeFormat('en-US', options).formatToParts(new Date());
var tzPart = parts.filter(function (p) { return p.type === 'timeZoneName'; })[0];
expectedAbbreviationLA = tzPart ? tzPart.value : nil;
} catch (e) {
[self fail:"Could not determine expected abbreviation for America/Los_Angeles"];
return;
@@ -385,4 +388,74 @@
[self assert:[timeZoneHNL abbreviation] equals:@"HST"];
}
// Pins the six timeDifferenceFromUTC entries corrected on CPTimeZoneTest-fix
// (MDT, MSK, NZDT, NZST, WAT, WIT) through the public API, so a regression
// back to any of the old wrong values is caught directly.
- (void)testCorrectedOffsets
{
[self assert:[[CPTimeZone timeZoneWithAbbreviation:@"MDT"] secondsFromGMT] equals:(-360 * 60)];
[self assert:[[CPTimeZone timeZoneWithAbbreviation:@"MSK"] secondsFromGMT] equals:(180 * 60)];
[self assert:[[CPTimeZone timeZoneWithAbbreviation:@"NZDT"] secondsFromGMT] equals:(780 * 60)];
[self assert:[[CPTimeZone timeZoneWithAbbreviation:@"NZST"] secondsFromGMT] equals:(720 * 60)];
[self assert:[[CPTimeZone timeZoneWithAbbreviation:@"WAT"] secondsFromGMT] equals:(60 * 60)];
[self assert:[[CPTimeZone timeZoneWithAbbreviation:@"WIT"] secondsFromGMT] equals:(420 * 60)];
}
// MSD ("Moscow Summer Time") has no correct current value: Russia abolished
// DST in 2014, so there is no live distinct summer offset for Moscow to
// assign. This pins the current, intentionally-unfixed value, so any future
// edit to it happens deliberately alongside CPTimeZone.j's comment and the
// tracked Intl redesign, not as a silent, unrelated drift.
- (void)testMSDKnownStaleValue
{
[self assert:[[CPTimeZone timeZoneWithAbbreviation:@"MSD"] secondsFromGMT] equals:(240 * 60)];
}
// knownTimeZoneNames should prefer the runtime's own IANA database over the
// old 48-city hardcoded list, on any engine that exposes
// Intl.supportedValuesOf. Skips itself where that API is unavailable, rather
// than asserting a specific engine capability.
- (void)testKnownTimeZoneNamesUsesIntlWhenAvailable
{
if (typeof Intl === "undefined" || typeof Intl.supportedValuesOf !== "function")
return;
var names = [CPTimeZone knownTimeZoneNames];
[self assertTrue:([names count] > 48)
message:"knownTimeZoneNames should use Intl.supportedValuesOf when available, not the small hardcoded fallback list"];
[self assertTrue:[names containsObject:@"Europe/Berlin"]
message:"a zone absent from the old hardcoded list should be present via Intl"];
}
// Disabled: the "fr" entry in localizedName is an empty dictionary, so any
// lookup for a French locale currently returns nil regardless of style. This
// is the same static, English-only table design as before the Intl
// migration; folding it in was deferred because CPTimeZoneNameStyleStandard/
// DaylightSaving need to force a specific state independent of the current
// date, which Intl.formatToParts(date) alone can't do for an arbitrary date.
// Tracked for the larger IANA-identity redesign, not fixed here.
- (void)disabled_testLocalizedNameFrenchLocale
{
var frenchLocale = [[CPLocale alloc] initWithLocaleIdentifier:@"fr_FR"],
timeZone = [CPTimeZone timeZoneWithAbbreviation:@"PST"];
[self assert:[timeZone localizedName:CPTimeZoneNameStyleStandard locale:frenchLocale] equals:@"Heure normale du Pacifique"];
}
// Disabled: timeZoneForSecondsFromGMT: does a linear scan of
// timeDifferenceFromUTC and returns the first matching key, with no defined
// tie-break when more than one abbreviation shares an offset. MDT and CST
// both now correctly resolve to -360; asking for that offset silently
// returns whichever CPDictionary happens to enumerate first, not a
// documented choice. The idealized contract is that an inherently ambiguous
// query should not silently guess one answer. No fix exists for this within
// the current flat abbreviation-to-offset table design.
- (void)disabled_testTimeZoneForSecondsFromGMTOffsetCollisionIsAmbiguous
{
var timeZone = [CPTimeZone timeZoneForSecondsFromGMT:(-360 * 60)];
[self assert:timeZone equals:nil];
}
@end