Reputation: 900
I am trying to get a Date
object for the next occurring future time where the hour in UTC time is 18. However my code doesn't work as expected. I have the following:
let dateComponents = DateComponents(timeZone: TimeZone(abbreviation: "GMT"), hour: 18)
let date = Calendar.current.nextDate(after: Date(), matching: dateComponents, matchingPolicy: .nextTime)
print(date)
The problem is that this results in 2019-02-09 23:00:00 +0000
The date is for the next occurring time where the hour is 18 in EST
.
I would have expected, since the the dateComponents
has the timezone set to UTC and the hour to 18, that the date would be 2019-02-09 18:00:00 +0000
. Furthermore, changing the timezone seems to have no effect on the nextDate
found.
Why doesn't the nextDate function respect the timezone set in the dateComponents
passed to it?
Upvotes: 2
Views: 501
Reputation: 49
It looks like the timezone in DateComponents is ignored. However when you set the timezone in a new calendar you get correct results.
let dateComponents = DateComponents(hour: 18)
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
let date = calendar.nextDate(after: Date(), matching: dateComponents, matchingPolicy: .nextTime)
print(date) // Optional(2020-09-29 18:00:00 +0000)
Upvotes: 2
Reputation: 8020
I live in GMT time, and running this in a playground produces the expected result you are looking for. You are setting the time zone of your date component, but I would imagine your own calendar (Calendar.current) is set to EST. You would need to account for the offset in EST vs GMT for your required result
Upvotes: 0