How to set seconds to zero for NSDate

cocoa-touch, ios, iphone, nsdate, objective-c

Solution

NSDate is immutable, so you cannot modify its time. But you can create a new date object that snaps to the nearest minute:

NSTimeInterval time = floor([date timeIntervalSinceReferenceDate] / 60.0) * 60.0;
NSDate *minute = [NSDate dateWithTimeIntervalSinceReferenceDate:time];

Edit to answer Uli's comment

The reference date for `NSDate` is January 1, 2001, 0:00 GMT. There have been two leap seconds added since then: 2005 and 2010, so the value returned by `[NSDate timeIntervalSinceReferenceDate]` should be off by two seconds.

This is not the case: `timeIntervalSinceReferenceDate` is exactly synchronous to the wall time.

When answering the question I did not make sure that this is actually true. I just assumed that Mac OS would behave as UNIX time (1970 epoch) does: POSIX guarantees that each day starts at a multiple of 86,400 seconds.

Looking at the values returned from `NSDate` this assumption seems to be correct but it sure would be nice to find a definite (documented) statement of that.

Problem

I'm trying to get `NSDate` from `UIDatePicker`, but it constantly returns me a date time with trailing 20 seconds. How can I manually set `NSDate`'s second to zero?

Original source