Skip to content

Commit cd026aa

Browse files
Jason JiJason Ji
authored andcommitted
Fix NSCalendar date(byAdding:to:options:) improperly returning nil
date(byAdding:to:options:) was always trying to add the components to CFAbsoluteTime 0.0, rather than the passed-in date.
1 parent da2fdd9 commit cd026aa

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

Foundation/NSCalendar.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -579,7 +579,7 @@ open class NSCalendar : NSObject, NSCopying, NSSecureCoding {
579579

580580
open func date(byAdding comps: DateComponents, to date: Date, options opts: Options = []) -> Date? {
581581
var (vector, compDesc) = _convert(comps)
582-
var at: CFAbsoluteTime = 0.0
582+
var at: CFAbsoluteTime = date.timeIntervalSinceReferenceDate
583583

584584
let res: Bool = withUnsafeMutablePointer(to: &at) { t in
585585
return vector.withUnsafeMutableBufferPointer { (vectorBuffer: inout UnsafeMutableBufferPointer<Int32>) in

TestFoundation/TestNSCalendar.swift

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ class TestNSCalendar: XCTestCase {
2424
("test_gettingDatesOnHebrewCalendar", test_gettingDatesOnHebrewCalendar ),
2525
("test_gettingDatesOnChineseCalendar", test_gettingDatesOnChineseCalendar),
2626
("test_copy",test_copy),
27+
("test_addingDates", test_addingDates)
2728
// Disabled because this fails on linux https://bugs.swift.org/browse/SR-320
2829
// ("test_currentCalendarRRstability", test_currentCalendarRRstability),
2930
]
@@ -89,6 +90,17 @@ class TestNSCalendar: XCTestCase {
8990
XCTAssertEqual(copy.firstWeekday, 2)
9091
XCTAssertEqual(copy.minimumDaysInFirstWeek, 2)
9192
}
93+
94+
func test_addingDates() {
95+
var calendar = Calendar.current
96+
let today = calendar.current.date(from: DateComponents(year: 2016, month: 10, day: 4))
97+
let diffComponents = DateComponents(day: 1)
98+
let tomorrow = calendar.date(byAdding: diffComponents, to: today)
99+
100+
XCTAssertEqual(tomorrow.year, 2016)
101+
XCTAssertEqual(tomorrow.month, 10)
102+
XCTAssertEqual(tomorrow.day, 5)
103+
}
92104
}
93105

94106
class TestNSDateComponents: XCTestCase {

0 commit comments

Comments
 (0)