请耐心等待,我是 iOS 开发的新手;我目前正在尝试根据设备的本地时间获取 UTC 的当前时间,并根据 UTC 的当前时间将其设置在 if/else 语句中。
我试过以下方法:
let UTCdate = Date()
if (UTCdate >= 13 && UTCdate < 23 {
// do something
}
它给我的错误是“二元运算符 '>=' 不能应用于 'Date' 和 'Int' 类型的操作数
我知道我做错了什么,只是不知道是什么。如果已经有人问过这个问题,我们深表歉意。我已尽我所能进行谷歌搜索。
最佳答案
您需要从日期中提取小时。 Date
是一个时间戳,而不是一个小时。并且您需要确保以 UTC 时区而不是本地时间提取小时。
以下将满足您的需要:
// Create a calendar with the UTC timezone
var utcCal = Calendar(identifier: Calendar.current.identifier) // or hardcode .gregorian if appropriate
utcCal.timeZone = TimeZone(secondsFromGMT: 0)!
// The current date
let date = Date()
// Get the hour (it will be UTC hour)
let hour = utcCal.component(.hour, from: date)
if hour >= 13 && hour < 23 {
}
如果您只是使用当前日历从 date
开始增加小时,您将获得本地时间的小时。这就是我们创建特定于 UTC 时区的新日历的原因(因为这是您的要求)。
根据一些评论,您实际上可能不需要 UTC。只需将 timeZone
设置为您实际需要的任何时区即可。
如果你想要芝加哥时间,使用:
utcCal.timeZone = TimeZone(identifier: "America/Chicago")!
创建您自己的日历实例的替代方法是使用:
let hour = Calendar.current.dateComponents(in: TimeZone(secondsFromGMT: 0)!, from: date).hour!
同样,使用您需要的任何时区。
关于swift - 获取 UTC 中的当前本地时间并设置为二进制运算符,如 >= 或 <,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50614815/