I have a bunch of Date
objects that I want to perform calculations on, for these calculations I dont need second precision so I am attempting to "zero out" the seconds on my Date
s. This all works fine unless the Date
already has zero seconds in which case Swift decrements the number of minutes by one, e.g 10:30:00 -> 10:29:00.
My code:
let calendar = Calendar.current
var minuteComponent = DateComponents()
minuteComponent.second = 0
let dateDelta = calendar.nextDate(after: date, matching: minuteComponent, matchingPolicy: .nextTime, direction: .backward)
I have tried all the matching policies only to get the same result.
This seems odd to me, as the target is already at the required value, though I suspect it is inline with the documentation.
Is this an appropriate way to zero out the seconds while preserving the higher magnitude components or is there a better way?
One option is to use a date formatter, since this cuts off the seconds it will be the same as rounding down.
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm"
let noSeconds = formatter.date(from: formatter.string(from: someDate))
And here is a similar solution using Calendar & DateComponents
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: someDate)
let noSeconds = calendar.date(from: components)