Skip to content

Commit e86c0dc

Browse files
committed
Fix DateFormatter TimeZone Setter
Because of the use of 'timeZone' instead of 'newValue' in the setter, setting the timeZone of a DateFormatter doesn't actually work. Instead, it winds up re-setting the old value, which happens to be whatever was originally set, usually what we get from copying the default down in CoreFoundation. Also adds a unit test to help prevent breaks like this again.
1 parent 59df77d commit e86c0dc

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

Foundation/DateFormatter.swift

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -176,13 +176,13 @@ open class DateFormatter : Formatter {
176176
/*@NSCopying*/ internal var _timeZone: TimeZone? { willSet { _reset() } }
177177
open var timeZone: TimeZone! {
178178
get {
179-
guard let timeZone = _timeZone else {
179+
guard let tz = _timeZone else {
180180
return (CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterTimeZone) as! NSTimeZone)._swiftObject
181181
}
182-
return timeZone
182+
return tz
183183
}
184184
set {
185-
_timeZone = timeZone
185+
_timeZone = newValue
186186
}
187187
}
188188

TestFoundation/TestDateFormatter.swift

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ class TestDateFormatter: XCTestCase {
2424
("test_dateFormatString", test_dateFormatString),
2525
("test_setLocaleToNil", test_setLocaleToNil),
2626
("test_setTimeZoneToNil", test_setTimeZoneToNil),
27+
("test_setTimeZone", test_setTimeZone),
2728
]
2829
}
2930

@@ -356,4 +357,22 @@ class TestDateFormatter: XCTestCase {
356357
// Time zone should go back to the system one.
357358
XCTAssertEqual(f.timeZone, NSTimeZone.system)
358359
}
360+
361+
func test_setTimeZone() {
362+
// Test two different time zones. Should ensure that if one
363+
// happens to be TimeZone.current, we still get a valid test.
364+
let newYork = TimeZone(identifier: "America/New_York")!
365+
let losAngeles = TimeZone(identifier: "America/Los_Angeles")!
366+
367+
XCTAssertNotEqual(newYork, losAngeles)
368+
369+
// Case 1: New York
370+
let f = DateFormatter()
371+
f.timeZone = newYork
372+
XCTAssertEqual(f.timeZone, newYork)
373+
374+
// Case 2: Los Angeles
375+
f.timeZone = losAngeles
376+
XCTAssertEqual(f.timeZone, losAngeles)
377+
}
359378
}

0 commit comments

Comments
 (0)