How to test Date with timezone aware in Swift
Issue #402
I want to test if a date has passed another date
1 | let base = Date(timeIntervalSince1970: 1567756697) |
My hasPassed
is using Calendar.current
1 | func minuteSinceMidnight(date: Date) -> MinuteSinceMidnight { |
But the minute is always having timezone applied. Even if I try with DateComponents
1 | func minuteSinceMidnight(date: Date) -> MinuteSinceMidnight { |
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 | let formatter = ISO8601DateFormatter() |
Another way is to have a fixed timezone for Calendar
1 | var calendar = Calendar.current |
Another way is to adjust existing date
1 | calendar.date(bySettingHour: 20, minute: 02, second: 00, of: Date() |