Search code examples
iosobjective-ccocoa-touchnsdatenstimeinterval

Get interval to last UTC midnight from an NSDate


I need to compare two times, but one is the current NSDate and the other is an NSTimeInterval. I need to trigger an action when the current time interval since the last UTC midnight gets larger than the given time interval. I'm happy with simply

NSDate *rightNowUTC = [[NSDate alloc] init];

to get current UTC NSDate, but I need to strip it down to "the time interval between whatever *now is and the last time midnight UTC occurred".


Solution

  • NSCalendar provides a method to get the start of the day (midnight) for a given date:

    NSDate *rightNowUTC = [[NSDate alloc] init];
    NSDate *midnight = [NSCalendar.currentCalendar startOfDayForDate: rightNowUTC];
    NSTimeInterval interval = [rightNowUTC timeIntervalSinceDate: midnight];