Search code examples
objective-cnsdatenstimeinterval

Objective-c format time left until certain date


I'm creating a countdown timer and I need to printout the time left (hour:minute:seconds) until a specific date. I've found how to get the time interval between Now and the target date but I don't know how to format the time interval as a string. Does NSDateFormater work on NSTimeInterval?


Solution

  • You would first compare two NSDate objects to retrieve the difference in seconds between the two, the NSDate method you should use is

    - (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate
    

    Then you could simply write a function to parse the seconds into hours/minutes/seconds, for example you could use this (untested):

    -(NSDictionary*)createTimemapForSeconds:(int)seconds{
       int hours = floor(seconds /  (60 * 60) );
    
       float minute_divisor = seconds % (60 * 60);
       int minutes = floor(minute_divisor / 60);
    
       float seconds_divisor = seconds % 60;
       seconds = ceil(seconds_divisor);
    
       NSDictionary * timeMap = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSNumber numberWithInt:hours], [NSNumber numberWithInt:minutes], [NSNumber numberWithInt:seconds], nil] forKeys:[NSArray arrayWithObjects:@"h", @"m", @"s", nil]];
    
       return timeMap;
    }