首页 > 解决方案 > 将当前时间向上舍入到下一个 30 分钟间隔

问题描述

我希望当前时间四舍五入到下一个 30 分钟间隔。例如:如果我在当前时间为晚上 8:33 打开应用程序,我希望接下来的 30 分钟时间为晚上 9:00。如果当前时间是 5 月 22 日晚上 11:30,则下一轮时间应该是 5 月 23 日上午 00 点。

我尝试使用下面的代码,但这给了我最近的一轮,即晚上 8:30。

我怎样才能得到下一轮的日期和时间?

func next30Mins() -> Date {
    return Date(timeIntervalSinceReferenceDate: (timeIntervalSinceReferenceDate / 1800.0).rounded(.toNearestOrEven) * 1800.0)
}

标签: iosswiftdate

解决方案


您可以获取日期分钟组件,检查它是否等于或大于 30 并返回 nextDate 分钟组件等于 0 否则等于 30:

extension Date {
    var minute: Int { Calendar.current.component(.minute, from: self) }
    var nextHalfHour: Date {
        Calendar.current.nextDate(after: self, matching: DateComponents(minute: minute >= 30 ? 0 : 30), matchingPolicy: .strict)!
    }
}

Date().nextHalfHour // "May 23, 2020 at 1:00 AM"

推荐阅读