swift - 检查本地时间是否在另一个时区的午夜之后

标签 swift time

我想检查我的本地时间是否在另一个时区的午夜之后。

具体来说,如果我现在所在的位置是本地时间周六晚上 11 点或周日凌晨 1 点,我想看看在中部时间(周日凌晨 12 点之后)是否是新一周的开始。

最佳答案

您可以使用CalendardateComponents(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/

相关文章:

iOS 约束方程值

ios - 我的代码有什么问题。我正在尝试为表格 View Controller 着色

c - 如何使用 clock_gettime 制作精确的倒数计时器?

Python time.sleep 语法错误

javascript - 获取两个日期时间之间的时间差

ios - 接线员 |不能应用于两个 "PFLoginFields"操作数 Swift

swift - 在Combine 中按顺序调用链式网络

arrays - Swift 获取所有用户到一个数组

Python:检查每小时的url请求

javascript - CSS 指示 "tensed"-div 是过去、现在还是 future ?