Swift日历类为工作日返回错误的日期 [英] Swift Calendar class returning wrong date for weekday

查看:56
本文介绍了Swift日历类为工作日返回错误的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Swift 3中的Calendar类有疑问.

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

请注意,我昨天测试了代码,这就是为什么我写今天是星期日"的原因.我原本以为第二种主要产品是2017年10月29日(下一个星期日),但是它给了我星期六.我在做什么错了?

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?

推荐答案

日期始终按照格林尼治标准时间(GMT)时区打印.

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

假设您的时区为UTC + 1,那么下一个星期日将为您所在时区的 29-10-2017 00:00:00 .但是,此 Date 实例在GMT中表示为 28-10-2017 23:00:00 .

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.

因此 nextDate 确实返回正确的日期,只是未在您的时区中格式化.要解决此问题,只需使用 DateFormatter :

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

这篇关于Swift日历类为工作日返回错误的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆