Skip to content

Commit f2672a7

Browse files
committed
Merge pull request #289 from seabaylea/nstimezone
Add implementation of NSTimeZone.init() with abbreviation
2 parents f59a5d4 + 7f598b1 commit f2672a7

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

Foundation/NSTimeZone.swift

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,13 @@ public class NSTimeZone : NSObject, NSCopying, NSSecureCoding, NSCoding {
8484
// do NOT follow the POSIX convention (of minutes-west).
8585
public convenience init(forSecondsFromGMT seconds: Int) { NSUnimplemented() }
8686

87-
public convenience init?(abbreviation: String) { NSUnimplemented() }
87+
public convenience init?(abbreviation: String) {
88+
let abbr = abbreviation._cfObject
89+
guard let name = unsafeBitCast(CFDictionaryGetValue(CFTimeZoneCopyAbbreviationDictionary(), unsafeBitCast(abbr, to: UnsafePointer<Void>.self)), to: NSString!.self) else {
90+
return nil
91+
}
92+
self.init(name: name._swiftObject , data: nil)
93+
}
8894

8995
public func encodeWithCoder(aCoder: NSCoder) {
9096
if aCoder.allowsKeyedCoding {

TestFoundation/TestNSTimeZone.swift

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ class TestNSTimeZone: XCTestCase {
2626
// Disabled see https://bugs.swift.org/browse/SR-300
2727
// ("test_abbreviation", test_abbreviation),
2828
("test_initializingTimeZoneWithOffset", test_initializingTimeZoneWithOffset),
29+
("test_initializingTimeZoneWithAbbreviation", test_initializingTimeZoneWithAbbreviation),
2930
// Also disabled due to https://bugs.swift.org/browse/SR-300
3031
// ("test_systemTimeZoneUsesSystemTime", test_systemTimeZoneUsesSystemTime),
3132
]
@@ -45,6 +46,16 @@ class TestNSTimeZone: XCTestCase {
4546
XCTAssertEqual(seconds, -14400, "GMT-0400 should be -14400 seconds but got \(seconds) instead")
4647
}
4748

49+
func test_initializingTimeZoneWithAbbreviation() {
50+
// Test invalid timezone abbreviation
51+
var tz = NSTimeZone(abbreviation: "XXX")
52+
XCTAssertNil(tz)
53+
// Test valid timezone abbreviation of "AST" for "America/Halifax"
54+
tz = NSTimeZone(abbreviation: "AST")
55+
let expectedName = "America/Halifax"
56+
XCTAssertEqual(tz?.name, expectedName, "expected name \"\(expectedName)\" is not equal to \"\(tz?.name)\"")
57+
}
58+
4859
func test_systemTimeZoneUsesSystemTime() {
4960
tzset();
5061
var t = time(nil)

0 commit comments

Comments
 (0)