Date and time formatting in iOS
I know NSDateFormatter but want it to resemble "Yesterday 12:35" and I only got it to execute two datestrings?
[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?
+3
source to share
1 answer
This is the best I could do while respecting 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]);
+2
source to share