Count with Me

While I’m transcoding video, I want to display the elapsed time in form:

3 minutes 34 seconds and 1 hour 32 minutes and 5 days 4 hours 23 minutes

I feared this problem. However, fifteen minutes of fumbling through Apple’s docs and I’ve got the answer in:

    [NSCalendarDate years.... sinceDate];

I love dreading a problem and then finding it to be super easy. So, assuming you had an NSCalendarDate from the past to get what I want, you’d do this:

    NSCalendarDate *twoHoursAgo = [NSCalendarDate 
                                    dateWithYear:2006 
                                    month:1 
                                    day:05 
                                    hour:14 
                                    minute:30 
                                    second:0 
                                    timeZone:nil];
    NSCalendarDate *now = [NSCalendarDate calendarDate];

int days, hours, minutes, seconds;
[[NSCalendarDate calendarDate] years:nil 
                            months:nil 
                            days:&days 
                            hours:&hours 
                            minutes:&minutes 
                            seconds:&seconds 
                            sinceDate:twoHoursAgo];

NSLog(@"%d days, %d hours, %dminutes and %d seconds", days, hours, minutes, seconds);

The output: 1 days, 0 hours, 52minutes and 33 seconds

Of course, to get things right you need to do some if(days)…else if(hours)…else junk to filter out the 0 entries. There may even be a simpler way (I first consulted the NSFormatter’s), but compared to what I was thinking I would have to do, this is a very welcome solution

Sincerely Yours, Another Happy Cocoa User.

Leave a Reply


© 2006-2009 roobasoft, LLC