NSCalendarUnitSecond returning zero

343 Views Asked by At

I have this method returning a string. But the seconds value is always zero. What am I doing wrong?

-(NSString*)secondsBetweenDate:(NSDate*)startDate andDate:(NSDate*)endDate {

    NSCalendar *calendar = [NSCalendar currentCalendar];
    unsigned int unitFlags = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;

    NSDateComponents *difference = [calendar components:unitFlags fromDate:startDate  toDate:endDate  options:0];

    long hour = [difference hour];
    long min = [difference minute];
    long sec = [difference second];
    NSLog(@"Hour: %ld Min: %ld Sec: %ld", hour, min, sec);
    return [NSString stringWithFormat:@"%02ld:%02ld:%02ld", hour, min, sec];
}
2

There are 2 best solutions below

0
On

Why don't you use the default NSDate difference calculations? Returns an NSTimeInterval which is in seconds:

typedef double NSTimeInterval; Description Used to specify a time interval, in seconds.

Operation is:

[aDate timeIntervalSinceDate:anotherDate];
0
On

Your code is correct. If you use the dates that actually differ in their seconds value it yields the expected results.

[self secondsBetweenDate:[NSDate dateWithTimeIntervalSinceNow:-99999] andDate:[NSDate date]];

logs:

Hour: 27 Min: 46 Sec: 39

And 99999 Seconds is 27*60*60 +46*60 +39


In our discussion in the comments we discovered that you had more of a conceptional problem. If you need to show a countdown or stopwatch type string you have to use the current time as one of the date parameters.

So if you want to show the time that has passed since a specific date (like a stop watch) you use:

NSDate *now = [NSDate date];
string = [self secondsBetweenDate:yourStartDate andDate:now];

If you want to show the time until a specific date (like a countdown) you use:

NSDate *now = [NSDate date];
string = [self secondsBetweenDate:now andDate:yourEndDate];

Btw: If you are only targetting iOS 8 and later you can use NSDateComponentsFormatter to format your date

NSDateComponentsFormatter *df = [[NSDateComponentsFormatter alloc] init];
df.unitsStyle = NSDateComponentsFormatterUnitsStylePositional;
df.allowedUnits =  NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSString *dateString = [df stringFromDate:startDate toDate:[NSDate date]];