How do I round a date to the nearest 5 minutes interval so that if for example the date's minute value is 33, then I round it to 35?
How do I round minutes to the nearest multiple of 5?
Add a Comment
How do I round a date to the nearest 5 minutes interval so that if for example the date's minute value is 33, then I round it to 35?
Very few
Date
questions have an easy answer, but this is one of them. Yay!
Under the covers
Date
is just a floating point count of the number of seconds since a reference date. If you round that count to the nearest 300.0, you get a five minute boundary.
For example:
let original = Date(timeIntervalSinceReferenceDate: 532956026.349427)
print(original) // prints: 2017-11-21 11:20:11 +0000
let rounded = Date(timeIntervalSinceReferenceDate: (original.timeIntervalSinceReferenceDate / 300.0).rounded(.toNearestOrEven) * 300.0)
print(rounded) // prints: 2017-11-21 11:20:00 +0000
This only works because:
All regions use the same concept of time, that is, hours, minutes and seconds. This stands in stark contrast to larger date components — like day, month and year — where different regions have very different calendars.
Date
ignores the concept of leap seconds.Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"