Chris Hansen
Chris Hansen

Reputation: 8655

Future Relative dates human readable form

How can I output human readable dates like turn NSDATE to human readable form like Tomorrow, one week from now, 1 month from now , etc?

For example if the current time is January 19, 2012 7 am

and the input date is January 20, 2012 9am

then the function should out Tomorrow at 9am.

I found how to do this with past dates online but not with future dates.

Also the functions I found online were not specific. Any help would be appreciated! thanks

Upvotes: 0

Views: 640

Answers (1)

sosborn
sosborn

Reputation: 14694

You need to use an NSDateFormatter. From the docs:

setDoesRelativeDateFormatting: Specifies whether the receiver uses phrases such as “today” and “tomorrow” for the date component.

- (void)setDoesRelativeDateFormatting:(BOOL)b

Parameters b YES to specify that the receiver should use relative date formatting, otherwise NO. Discussion If a date formatter uses relative date formatting, where possible it replaces the date component of its output with a phrase—such as “today” or “tomorrow”—that indicates a relative date. The available phrases depend on the locale for the date formatter; whereas, for dates in the future, English may only allow “tomorrow,” French may allow “the day after the day after tomorrow,” as illustrated in the following example.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSLocale *frLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"];
[dateFormatter setLocale:frLocale];

[dateFormatter setDoesRelativeDateFormatting:YES];

NSDate *date = [NSDate dateWithTimeIntervalSinceNow:60*60*24*3];
NSString *dateString = [dateFormatter stringFromDate:date];

NSLog(@"dateString: %@", dateString);
// Output
// dateString: après-après-demain

Upvotes: 2

Related Questions