Swift Calendar class returning wrong date for weekday

夙愿已清 提交于 2021-02-08 10:40:58

问题


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?


回答1:


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))


来源:https://stackoverflow.com/questions/46890038/swift-calendar-class-returning-wrong-date-for-weekday

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!