Search code examples
objective-ccocoansdatenscalendar

How to clear NSDate milliseconds


I want to keep date/times in a CoreData store with no seconds or milliseconds. (I'm doing some processing to round times off, and stray seconds/milliseconds become a monkey wrench.) It's easy enough to drop the seconds:

NSDate *now = [NSDate date];
NSDateComponents *time = [[NSCalendar currentCalendar]
                          components:NSHourCalendarUnit | NSMinuteCalendarUnit 
                          | NSSecondCalendarUnit fromDate:now];
    NSDate *nowMinus = [now addTimeInterval:-time.second];
    // e.g. 29 Aug 10 4:43:05 -> 29 Aug 10 4:43:00

This works great to zero out the seconds, but I can't find an NSMillisecondCalendarUnit I could use to zero out the milliseconds, and I need to. Any ideas? Thanks.


Solution

  • timeIntervalSince1970 returns the number of seconds (in a double) since January the 1st, 1970. You can use this time to truncate any amount of seconds you like. To round down to the nearest minute, you could do:

    NSTimeInterval timeSince1970 = [[NSDate date] timeIntervalSince1970];
    
    timeSince1970 -= fmod(timeSince1970, 60); // subtract away any extra seconds
    
    NSDate *nowMinus = [NSDate dateWithTimeIntervalSince1970:timeSince1970];
    

    Floating point data types are inherently imprecise, but the above may be precise enough for your needs.