Karsten
Karsten

Reputation: 1939

Date and time formatting in iOS

I know the NSDateFormatter but I want it like "Yesterday 12:35" and I only got it you concatting two datestring?

[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setLocale: [NSLocale autoupdatingCurrentLocale]];

[dateFormatter setDoesRelativeDateFormatting:YES];

[dateFormatterTime setLocale:[NSLocale systemLocale]];
[dateFormatterTime setDateFormat:@"HH:mm"];

NSString *dateString = [NSString stringWithFormat:@"%@ %@", [dateFormatter stringFromDate:dateParsed], [dateFormatterTime stringFromDate:dateParsed ] ];

Any ideas?

Upvotes: 3

Views: 1804

Answers (1)

Larry Aasen
Larry Aasen

Reputation: 515

This is the best I could do by honoring the locale.

NSDateFormatter *dateFormatter = NSDateFormatter.new;
dateFormatter.doesRelativeDateFormatting = YES;
dateFormatter.dateStyle = NSDateFormatterShortStyle;
dateFormatter.timeStyle = NSDateFormatterShortStyle;

NSDate *today = NSDate.new;
// "Today, 11:40 AM"
NSLog(@"%@", [dateFormatter stringFromDate:today]);

NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:60*60*24];
// "Tomorrow, 11:40 AM"
NSLog(@"%@", [dateFormatter stringFromDate:tomorrow]);

NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow:-(60*60*24)];
// "Yesterday, 11:40 AM"
NSLog(@"%@", [dateFormatter stringFromDate:yesterday]);

NSDate *dayAfter = [NSDate dateWithTimeIntervalSinceNow:(60*60*24)*2];
// "2/14/13, 11:40 AM"
NSLog(@"%@", [dateFormatter stringFromDate:dayAfter]);

Upvotes: 2

Related Questions