Louie
Louie

Reputation: 5940

Convert NSString to a Time, and then calculate "Time Until"

I have been on SO for awhile now trying to get this problem solved but have not had any luck.

In a nutshell I want to take a string like this: "2011-11-21 11:20:00" and calculate the "Time Until". In a format like "1 day 36 mins" which would be a string I could display in a label.

I cant wrap my head around this. Anyone have some sample code from doing this before? Any help would be greatly appreciated.

Upvotes: 2

Views: 408

Answers (3)

Mohit Tomar
Mohit Tomar

Reputation: 5201

duration.text = [NSString stringWithFormat:@"%d:%02d", (int)audioPlayer.duration / 3600, (int)audioPlayer.duration % 60, nil];

Upvotes: 1

Jesse Black
Jesse Black

Reputation: 7976

This code should help you out.

    NSDate * date;

    //Assume dateString is populated and of format NSString * dateString =@"2011-11-21 11:20:00";
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];

    //EDITED date formatter to correct behavior
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    if (dateString != nil)  {
        date = [dateFormatter dateFromString:dateString];
    }
    [dateFormatter release];

    NSTimeInterval difference = [date timeIntervalSinceDate:[NSDate date]];
    int days = difference/(3600*24);
    difference -= (float) (days*3600*24);
    int hours = difference/(3600);
    difference -= (float) (hours*3600);
    int minutes = difference/(60);

    NSString * timeRemaining = [NSString stringWithFormat:@"%dd %dh %dm", days, hours, minutes];

Upvotes: 2

Dave DeLong
Dave DeLong

Reputation: 243146

@Maudicus is on the right track but has some flaws in his answer.

  1. The date format you'd need to use is @"yyyy-MM-dd HH:mm:ss"
  2. Once you have the date, you should use -[NSCalendar components:fromDate:toDate:options:] to figure out the differences between one date and another. For example:

    NSDate *date = ...; // the date converted using the date formatter
    NSDate *target = [NSDate date]; // now
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger components = NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *difference = [calendar components:components fromDate:date toDate:target options:0];
    
    NSLog(@"difference: %d days, %d hours, %d minutes, %d seconds", [difference days], [difference hours], [difference minutes], [difference seconds]);
    

Upvotes: 3

Related Questions