Created
September 21, 2009 06:35
-
-
Save sukima/190106 to your computer and use it in GitHub Desktop.
How to extract elapsed time from NSDate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// - since {{{ | |
- (NSString *)since | |
{ | |
// seed the test data. (in future passed in via a class instance variable) | |
NSString *dateStr = @"Mon May 05 17:26:30 +0000 2008"; | |
// create our fommating object | |
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease]; | |
[dateFormat setDateFormat:@"EEE MMM dd HH:mm:ss Z yyyy"]; | |
// create a date from the above string. | |
NSDate *date = [dateFormat dateFromString:dateStr]; | |
// seconds between date and now. (cast to int) | |
int timeSinceNow = (int) [date timeIntervalSinceNow]; | |
// convert negative to positive. | |
if (timeSinceNow < 0) | |
{ | |
timeSinceNow = timeSinceNow * -1; | |
} | |
// is interval less then a minute? print seconds. | |
if (timeSinceNow < 60) | |
{ | |
NSString *plural = (timeSinceNow > 1) ? @"s" : @""; | |
return [NSString stringWithFormat:@"%d second%@ ago", | |
round( timeSinceNow ), plural]; | |
} | |
// is interval less then an hour? print minutes. | |
else if (timeSinceNow < 60 * 60) | |
{ | |
int minutes = round( timeSinceNow / 60 ); | |
NSString *plural = (minutes > 1) ? @"s" : @""; | |
return [NSString stringWithFormat:@"%d minute%@ ago", minutes, plural]; | |
} | |
// is interval less then a day? print hours and minutes. | |
else if (timeSinceNow < 60 * 60 * 24) | |
{ | |
int hours = round( timeSinceNow / (60 * 60) ); | |
NSString *pluralHours = (hours > 1) ? @"s" : @""; | |
int minutes = round( ( timeSinceNow - (60 * 60) ) / 60 ); | |
NSString *pluralMinutes = (minutes > 1) ? @"s" : @""; | |
return [NSString stringWithFormat:@"%d hour%@ and %d minute%@ ago", | |
hours, pluralHours, minutes, pluralMinutes]; | |
} | |
// more then a day? print formatted date. | |
else | |
{ | |
[dateFormat setDateStyle:NSDateFormatterShortStyle]; | |
[dateFormat setTimeStyle:NSDateFormatterShortStyle]; | |
return [dateFormat stringFromDate:date]; | |
} | |
} //}}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment