mirror of
https://github.com/cappuccino/cappuccino.git
synced 2026-11-20 21:49:22 +00:00
Merge pull request #3299 from enquora/CPTimeZoneTest-fix
Fixes: CPTimeZoneTest, CPTimeZone, and CPDate
This commit is contained in:
3 files changed
+223
-108
No files matched your search
+19
-16
@@ -109,28 +109,31 @@ var CPDateReferenceDate = new Date(Date.UTC(2001, 0, 1, 0, 0, 0, 0));
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns a CPDate initialized with a date and time specified by the given
|
||||
string in international date format YYYY-MM-DD HH:MM:SS ±HHMM (e.g.
|
||||
2009-11-17 17:52:04 +0000).
|
||||
Returns a CPDate initialized with a date and time specified by the given
|
||||
string in international date format YYYY-MM-DD HH:MM:SS ±HHMM (e.g.
|
||||
2009-11-17 17:52:04 +0000).
|
||||
|
||||
The offset is taken verbatim from the string; the result does not depend
|
||||
on the host's local time zone or any CPTimeZone data. Callers needing an
|
||||
offset derived from an actual IANA zone (e.g. accounting for DST) are
|
||||
responsible for resolving it themselves via the browser's Intl API before
|
||||
constructing the string.
|
||||
*/
|
||||
- (id)initWithString:(CPString)description
|
||||
{
|
||||
var format = new RegExp("(\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2}) ([-+])(\\d{2})(\\d{2})"),
|
||||
d = description.match(new RegExp(format));
|
||||
var format = new RegExp("(\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2}) ([-+])(\\d{2})(\\d{2})"),
|
||||
d = description.match(format);
|
||||
|
||||
if (!d || d.length != 10)
|
||||
[CPException raise:CPInvalidArgumentException
|
||||
reason:"initWithString: the string must be in YYYY-MM-DD HH:MM:SS ±HHMM format"];
|
||||
if (!d || d.length != 10)
|
||||
[CPException raise:CPInvalidArgumentException
|
||||
reason:"initWithString: the string must be in YYYY-MM-DD HH:MM:SS ±HHMM format"];
|
||||
|
||||
var date = new Date(d[1], d[2] - 1, d[3]),
|
||||
timeZoneOffset = (Number(d[8]) * 60 + Number(d[9])) * (d[7] === '-' ? 1 : -1);
|
||||
var timeZoneOffsetMinutes = (Number(d[8]) * 60 + Number(d[9])) * (d[7] === '-' ? 1 : -1),
|
||||
utcMillis = Date.UTC(Number(d[1]), Number(d[2]) - 1, Number(d[3]),
|
||||
Number(d[4]), Number(d[5]), Number(d[6]));
|
||||
|
||||
date.setHours(d[4]);
|
||||
date.setMinutes(d[5]);
|
||||
date.setSeconds(d[6]);
|
||||
|
||||
self = new Date(date.getTime() + (timeZoneOffset - date.getTimezoneOffset()) * 60 * 1000);
|
||||
return self;
|
||||
self = new Date(utcMillis + timeZoneOffsetMinutes * 60 * 1000);
|
||||
return self;
|
||||
}
|
||||
|
||||
- (CPTimeInterval)timeIntervalSinceDate:(CPDate)anotherDate
|
||||
|
||||
+126
-87
@@ -47,30 +47,25 @@ 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();
|
||||
// First, 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 the next attempt.
|
||||
}
|
||||
|
||||
// Strategy 2: If string parsing fails (e.g., for "GMT-04:00"), use the modern and reliable Intl API.
|
||||
// If that short name 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
|
||||
@@ -98,8 +93,22 @@ function abbreviationForDate(date)
|
||||
if (possibleAbbrs.length > 0) {
|
||||
return possibleAbbrs[0];
|
||||
}
|
||||
|
||||
// Neither attempt above found a match by name. Fall back to any
|
||||
// known abbreviation whose stored offset matches the system's
|
||||
// current UTC offset. Several abbreviations legitimately share an
|
||||
// offset (GMT, UTC, and WET all correctly resolve to 0, for example),
|
||||
// so this returns one of them rather than none.
|
||||
var offsetKeys = [timeDifferenceFromUTC keyEnumerator],
|
||||
offsetKey;
|
||||
|
||||
while (offsetKey = [offsetKeys nextObject]) {
|
||||
if ([timeDifferenceFromUTC valueForKey:offsetKey] === currentOffset) {
|
||||
return offsetKey;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// Intl API not supported, or it failed. We cannot proceed with this strategy.
|
||||
// Intl API not supported, or it failed.
|
||||
}
|
||||
|
||||
// Return nil if no valid abbreviation could be determined.
|
||||
@@ -108,28 +117,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;
|
||||
}
|
||||
}
|
||||
@@ -155,56 +154,94 @@ function _abbreviationForNameAndDate(tzName, date)
|
||||
return;
|
||||
|
||||
knownTimeZoneNames = [
|
||||
@"America/Halifax",
|
||||
@"America/Juneau",
|
||||
@"America/Juneau",
|
||||
@"America/Argentina/Buenos_Aires",
|
||||
@"America/Halifax",
|
||||
@"Asia/Dhaka",
|
||||
@"America/Sao_Paulo",
|
||||
@"America/Sao_Paulo",
|
||||
@"Europe/London",
|
||||
@"Africa/Addis_Ababa",
|
||||
@"Africa/Harare",
|
||||
@"America/Chicago",
|
||||
@"Europe/Paris",
|
||||
@"Europe/Paris",
|
||||
@"America/Santiago",
|
||||
@"America/Santiago",
|
||||
@"Africa/Lagos",
|
||||
@"America/Argentina/Buenos_Aires",
|
||||
@"America/Bogota",
|
||||
@"America/Chicago",
|
||||
@"Africa/Addis_Ababa",
|
||||
@"America/Denver",
|
||||
@"America/Halifax",
|
||||
@"America/Juneau",
|
||||
@"America/Lima",
|
||||
@"America/Los_Angeles",
|
||||
@"America/New_York",
|
||||
@"Europe/Istanbul",
|
||||
@"Europe/Istanbul",
|
||||
@"America/New_York",
|
||||
@"GMT",
|
||||
@"America/Santiago",
|
||||
@"America/Sao_Paulo",
|
||||
@"Asia/Bangkok",
|
||||
@"Asia/Calcutta",
|
||||
@"Asia/Dhaka",
|
||||
@"Asia/Dubai",
|
||||
@"Asia/Hong_Kong",
|
||||
@"Pacific/Honolulu",
|
||||
@"Asia/Bangkok",
|
||||
@"Asia/Tehran",
|
||||
@"Asia/Calcutta",
|
||||
@"Asia/Tokyo",
|
||||
@"Asia/Seoul",
|
||||
@"America/Denver",
|
||||
@"Europe/Moscow",
|
||||
@"Europe/Moscow",
|
||||
@"America/Denver",
|
||||
@"Pacific/Auckland",
|
||||
@"Pacific/Auckland",
|
||||
@"America/Los_Angeles",
|
||||
@"America/Lima",
|
||||
@"Asia/Manila",
|
||||
@"Asia/Jakarta",
|
||||
@"Asia/Karachi",
|
||||
@"America/Los_Angeles",
|
||||
@"Asia/Manila",
|
||||
@"Asia/Seoul",
|
||||
@"Asia/Singapore",
|
||||
@"Asia/Tehran",
|
||||
@"Asia/Tokyo",
|
||||
@"Europe/Istanbul",
|
||||
@"Europe/Lisbon",
|
||||
@"Europe/London",
|
||||
@"Europe/Moscow",
|
||||
@"Europe/Paris",
|
||||
@"GMT",
|
||||
@"Pacific/Auckland",
|
||||
@"Pacific/Honolulu",
|
||||
@"UTC",
|
||||
@"Africa/Lagos",
|
||||
@"Europe/Lisbon",
|
||||
@"Europe/Lisbon",
|
||||
@"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)
|
||||
{
|
||||
var zones = [];
|
||||
var hasGMT = false;
|
||||
var hasUTC = false;
|
||||
var count = supportedZones.length;
|
||||
|
||||
// Iterate using primitive property access.
|
||||
// The array returned by Intl across the runtime bridge may lack
|
||||
// standard Array prototypes (e.g., slice, indexOf). A standard loop
|
||||
// ensures safe data extraction into a local array without triggering
|
||||
// prototype resolution exceptions or relying on CPArray.
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var zone = supportedZones[i];
|
||||
zones[i] = zone;
|
||||
|
||||
if (zone === @"GMT")
|
||||
hasGMT = true;
|
||||
else if (zone === @"UTC")
|
||||
hasUTC = true;
|
||||
}
|
||||
|
||||
// Explicitly restore legacy aliases if the host engine omits them.
|
||||
// Engines adhering strictly to canonical IANA identifiers omit "GMT"
|
||||
// and "UTC". CPTimeZone's static dictionaries map these directly,
|
||||
// requiring their presence to initialize localTimeZone in UTC environments.
|
||||
if (!hasGMT)
|
||||
zones[zones.length] = @"GMT";
|
||||
|
||||
if (!hasUTC)
|
||||
zones[zones.length] = @"UTC";
|
||||
|
||||
knownTimeZoneNames = zones;
|
||||
}
|
||||
}
|
||||
catch (e)
|
||||
{
|
||||
// Fall through, keep the hardcoded list above.
|
||||
}
|
||||
}
|
||||
|
||||
abbreviationDictionary = @{
|
||||
@"ADT" : @"America/Halifax",
|
||||
@"AKDT" : @"America/Juneau",
|
||||
@@ -289,12 +326,14 @@ function _abbreviationForNameAndDate(tzName, date)
|
||||
@"IST" : 330,
|
||||
@"JST" : 540,
|
||||
@"KST" : 540,
|
||||
@"MDT" : -300,
|
||||
@"MSD" : 240,
|
||||
@"MSK" : 240,
|
||||
@"MDT" : -360,
|
||||
@"MSD" : 240, // Stale: Russia abolished DST in 2014. No current offset
|
||||
// is correct for a distinct "Moscow Summer Time"; left
|
||||
// unfixed rather than fabricated. See CPTimeZone redesign.
|
||||
@"MSK" : 180,
|
||||
@"MST" : -420,
|
||||
@"NZDT" : 900,
|
||||
@"NZST" : 900,
|
||||
@"NZDT" : 780,
|
||||
@"NZST" : 720,
|
||||
@"PDT" : -420,
|
||||
@"PET" : -300,
|
||||
@"PHT" : 480,
|
||||
@@ -302,10 +341,10 @@ function _abbreviationForNameAndDate(tzName, date)
|
||||
@"PST" : -480,
|
||||
@"SGT" : 480,
|
||||
@"UTC" : 0,
|
||||
@"WAT" : -540,
|
||||
@"WAT" : 60,
|
||||
@"WEST" : 60,
|
||||
@"WET" : 0,
|
||||
@"WIT" : 540
|
||||
@"WIT" : 420
|
||||
};
|
||||
|
||||
var englishLocalizedName = @{
|
||||
|
||||
@@ -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
|
||||
Reference in new issue
Block a user