我要现在的时间集中到下一个30分钟的间隔。如果我打开当前时间为晚上8:33的应用程序,我希望接下来30分钟的时间是晚上9:00。如果现在的时间是5月22日晚上11:30,下一轮的时间应该是5月23日。
我尝试了下面的代码,但这给了我最近的一轮,也就是晚上8:30。
我怎样才能得到下一轮的日期和时间?
func next30Mins() -> Date {
return Date(timeIntervalSinceReferenceDate: (timeIntervalSinceReferenceDate / 1800.0).rounded(.toNearestOrEven) * 1800.0)
}
发布于 2020-05-23 03:45:51
您可以获得日期分钟组件,检查它是否等于或超过30,然后返回包含分钟组件等于零的nextDate,否则等于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"
https://stackoverflow.com/questions/61967112
复制相似问题