How to test Date with timezone aware in Swift

Issue #402

I want to test if a date has passed another date

1
2
let base =  Date(timeIntervalSince1970: 1567756697)
XCTAssertEqual(validator.hasPassed(event: event, date: base), true)

My hasPassed is using Calendar.current

1
2
3
4
5
func minuteSinceMidnight(date: Date) -> MinuteSinceMidnight {
let calendar = Calendar.current
let start = calendar.startOfDay(for: date)
return Int(date.timeIntervalSince(start)) / 60
}

But the minute is always having timezone applied. Even if I try with DateComponents

1
2
3
4
5
6
7
8
func minuteSinceMidnight(date: Date) -> MinuteSinceMidnight {
let components = calendar.dateComponents([.hour, .minute], from: date)
guard let hour = components.hour, let minute = components.minute else {
return 0
}

return hour * 60 + minute
}

As long as I use Calendar, it always has timezone applied.

Checking this time interval 1567756697 on https://www.epochconverter.com/

Assuming that this timestamp is in seconds:
GMT: Friday, September 6, 2019 7:58:17 PM
Your time zone: Friday, September 6, 2019 9:58:17 PM GMT+02:00 DST

Because I have GMT+2, there will always be 2 hours offset. This works in app, but not in test because of the way I construct Date with time interval.

One way is to have test data using string construction, and provide timezone to DateFormatter

1
2
3
let formatter = ISO8601DateFormatter()
let date = formatter.date(from: "2019-07-58T12:39:00Z")
let string = formatter.string(from: Date())

Another way is to have a fixed timezone for Calendar

1
2
var calendar = Calendar.current
calendar.timeZone = TimeZone(secondsFromGMT: 0)!

Another way is to adjust existing date

1
calendar.date(bySettingHour: 20, minute: 02, second: 00, of: Date()

Comments