I want to return my date objects with string “today” and “yesterday” and dates in Objective C.Please all comments are welcome:
I have dates with format @"yyyy-MM-dd HH:mm:ss"] and then figures out if the date is today or yesterday and than, if it is, it returns "(Yesterday | Today | Date ) " formated string.
NSDateFormatter can do this. However this does not work with custom date formats, but in most cases when you need relative dates you are presenting them to the user and you should not use hard coded date formats in the first place.
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.timeStyle = NSDateFormatterMediumStyle;
df.dateStyle = NSDateFormatterShortStyle;
df.doesRelativeDateFormatting = YES; // this enables relative dates like yesterday, today, tomorrow...
NSLog(@"%@", [df stringFromDate:[NSDate dateWithTimeIntervalSinceNow:-48*60*60]]);
NSLog(@"%@", [df stringFromDate:[NSDate dateWithTimeIntervalSinceNow:-24*60*60]]);
NSLog(@"%@", [df stringFromDate:[NSDate date]]);
NSLog(@"%@", [df stringFromDate:[NSDate dateWithTimeIntervalSinceNow:24*60*60]]);
NSLog(@"%@", [df stringFromDate:[NSDate dateWithTimeIntervalSinceNow:48*60*60]]);
this will print:
2013-06-06 09:13:22.844 x 2[11732:c07] 6/4/13, 9:13:22 AM
2013-06-06 09:13:22.845 x 2[11732:c07] Yesterday, 9:13:22 AM
2013-06-06 09:13:22.845 x 2[11732:c07] Today, 9:13:22 AM
2013-06-06 09:13:22.846 x 2[11732:c07] Tomorrow, 9:13:22 AM
2013-06-06 09:13:22.846 x 2[11732:c07] 6/8/13, 9:13:22 AM
On a device with german locale this will print "Vorgestern" (the day before yesterday) and "Übermorgen" (the day after tomorrow) for the first and last date.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With