我想检查我的本地时间是否在另一个时区的午夜之后。
具体来说,如果我现在所在的位置是本地时间周六晚上 11 点或周日凌晨 1 点,我想看看在中部时间(周日凌晨 12 点之后)是否是新一周的开始。
最佳答案
您可以使用Calendar
的dateComponents(in: TimeZone, from: Date)
来检查另一个时区的时间和日期。对于您的特定应用:
// create current date, central time zone, and get the current calendar
let now = Date()
let centralTimeZone = TimeZone(abbreviation: "CST")!
let calendar = Calendar.current
let components = calendar.dateComponents(in: centralTimeZone, from: now)
if components.weekday == 1 {
print("It is Sunday in Central Standard Time.")
} else {
print("It is not Sunday in Central Standard Time.")
}
你在那里做的是要求当前日历给你一整套 DateComponents在指定的时区。然后 components.weekday
以 Int 形式给出星期几,从 1 开始表示公历中的星期日。
如果您想更广泛地了解某个地方是否是“明天”,这里有一个简单的方法:
func isItTomorrow(in zone: TimeZone) -> Bool {
var calendarInZone = Calendar(identifier: Calendar.current.identifier)
calendarInZone.timeZone = TimeZone(abbreviation: "CST")!
return calendarInZone.isDateInTomorrow(Date())
}
if isItTomorrow(in: centralTimeZone) {
print("It is tomorrow.")
} else {
print("It is not tomorrow.")
}
isItTomorrow(in: TimeZone)
创建一个与当前日历类型相同的新日历(大概是 .gregorian
,但你永远不知道)并将其时区设置为想要的那个。然后它使用简洁的内置 Calendar
方法 .isDateInTomorrow()
检查当前时间是否为目标时区的“明天”。
还有很多其他方法可以做到这一点,根据您的具体需要,可能有一种内置方法可以为您节省大量工作,因此非常值得阅读 Calendar 上的文档。和 DateComponents查看可用的内容。
关于swift - 检查本地时间是否在另一个时区的午夜之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45362849/