问题
I want current time to round up to next 30 mins interval. Eg: If I open the app with current time as 8:33pm, I want next 30 mins round up time to be 9:00pm. If current time is May 22 11:30pm, next round up time should be May 23 00am.
I tried with below code, but that gives me the nearest round up which is 8:30pm.
How can I get next round up date and time?
func next30Mins() -> Date {
return Date(timeIntervalSinceReferenceDate: (timeIntervalSinceReferenceDate / 1800.0).rounded(.toNearestOrEven) * 1800.0)
}
回答1:
You can get the date minute component, check if it is equal or more than 30 and return the nextDate with minute component equal to zero otherwise equal to 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/round-up-current-time-to-next-30-mins-interval