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.
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];