ios - 将当前时间向上舍入到下一个 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)
}
解决方案
您可以获取日期分钟组件,检查它是否等于或大于 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"
推荐阅读
- linq - 有没有办法使用 Entity Framework Core 在数据库端获取 ulong 的总和?
- c# - TapGestureRecognizer 在 iOS 和 UWP 中不起作用
- php - 如何使用 php 保存图像源变量
- java - Flux 在任何 java.lang.Error(OOM) 的情况下卡住
- spring-data-mongodb - Spring Data 索引自动创建
- excel - 我的同事的运行时 1004 错误,但不是我的
- tensorflow - 为什么加载具有 LSTM 初始状态的 TF Keras 模型不起作用?
- git - 如何在 GitHub 中显示被视为“二进制”的文件的差异?
- python - 所有订单均未显示
- swift - SwiftUI WindowGroup:如何限制窗口数量?