KO70
KO70

Reputation: 187

Swift Calendar class returning wrong date for weekday

I have a question regarding the Calendar class in Swift 3:

Basically, I wanted to get the Date of the next Sunday. However, the following code gives me the wrong output:

let cal = Calendar.current //gregorian
let today = Date(timeIntervalSinceNow: 0)
let date_c = DateComponents(calendar: cal, weekday: 1)

let today_weekday = cal.component(Calendar.Component.weekday, from: today)
let next_sunday = cal.nextDate(after: today, matching: date_c, matchingPolicy: Calendar.MatchingPolicy.nextTime)!

print(today_weekday) //prints out: 1 (today is Sunday, that's true)
print(next_sunday) //prints out: 2017-10-28 which is a Saturday

Please note that I tested the code yesterday, that's why I wrote "today is Sunday". I was expecting the second print output to be the 2017-10-29 (next Sunday) however, it is giving me Saturday. What am I doing wrong?

Upvotes: 0

Views: 1418

Answers (1)

Sweeper
Sweeper

Reputation: 271070

Dates are always printed as if they are in the GMT timezone.

Suppose your time zone is UTC+1, then next Sunday will be 29-10-2017 00:00:00 in your time zone. However, this Date instance is expressed as 28-10-2017 23:00:00 in GMT.

So nextDate does return the correct date, it's just not formatted in your time zone. To fix this, just use a DateFormatter:

let formatter = DateFormatter()
formatter.dateStyle = .short
print(formatter.string(from: next_sunday))

Upvotes: 3

Related Questions