12

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.

Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247
Ananya
  • 345
  • 2
  • 5
  • 15
  • If the date before yesterday what will be the output. Please tell what exactly you want. – Prateek Prem Jun 06 '13 at 06:48
  • if date before yesterday it need to show the date itself..i want to return the strings with today,yesterday and the date itself.. – Ananya Jun 06 '13 at 06:50

6 Answers6

26

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.

Community
  • 1
  • 1
Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247
5

What about NSDateFormatters setDoesRelativeDateFormatting ?

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

- (void)setDoesRelativeDateFormatting:(BOOL)b
Set parameters b = YES to specify that the receiver should use relative date formatting, otherwise NO.

Take a look: NSDateFormatter class reference

Vegar
  • 12,828
  • 16
  • 85
  • 151
3

I hope this also will be usefull for you as well:

    NSDate *date = somedate;
    NSInteger dayDiff = (int)[date timeIntervalSinceNow] / (60*60*24);
    NSDateComponents *componentsToday = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
    NSDateComponents *componentsDate = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:somedate];
    NSInteger day = [componentsToday day] - [componentsDate day];
    if (dayDiff == 0) {
        NSLog(@"Today");
    } else if (dayDiff == -1) {
        NSLog(@"Yesterday");
    } else if(dayDiff > -7 && dayDiff < -1) {
        NSLog(@"This week");
    } else if(dayDiff > -14 && dayDiff <= -7) {
        NSLog(@"Last week");
    } else if(dayDiff >= -60 && dayDiff <= -30) {
        NSLog(@"Last month");
    } else {
        NSLog(@"A long time ago");
    }
Bob
  • 1,351
  • 11
  • 28
  • 1
    Not quite correct. Your code will label 11pm yesterday, as being "Today", if the current time is anytime before 11pm. The correct definition of "Yesterday" is any time between midnight last night and the midnight of the night before. Not 24 hours before now. – mahboudz Oct 02 '14 at 21:00
2

Replacement of date object with “today” and “yesterday” strings in Swift.

If you want to display date with different formate then change the timeStyle and dateStyle as per you need.

var df = DateFormatter()
df.timeStyle = .medium
df.dateStyle = .short
df.doesRelativeDateFormatting = true
// this enables relative dates like yesterday, today, tomorrow...
print("\(df.string(from: Date(timeIntervalSinceNow: -48 * 60 * 60)))")
print("\(df.string(from: Date(timeIntervalSinceNow: -24 * 60 * 60)))")
print("\(df.string(from: Date()))")
print("\(df.string(from: Date(timeIntervalSinceNow: 24 * 60 * 60)))")
print("\(df.string(from: Date(timeIntervalSinceNow: 48 * 60 * 60)))")

Result:

6/4/13, 9:13:22 AM 
Yesterday, 9:13:22 AM 
Today, 9:13:22 AM
Tomorrow, 9:13:22 AM 
6/8/13, 9:13:22 AM
kuldip bhalodiya
  • 992
  • 7
  • 11
0
    NSDate *todayDate = [NSDate date];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *today = [dateFormat stringFromDate:todayDate];
    NSLog(@"today is %@",today);
    NSDate *yesterdayDate = [todayDate dateByAddingTimeInterval: -86400.0];
    NSString *yesterday = [dateFormat stringFromDate:yesterdayDate];
    NSLog(@"yesterday was %@",yesterday);

    NSString *yourDate = [NSString stringWithFormat:@"2013-06-08 12:33:28"];

    if ([yourDate isEqualToString:yesterday]) {

        NSLog(@"yesterday");
    }
    else if ([yourDate isEqualToString:today])
    {
        NSLog(@"today");

    }
    else
    {
        NSLog(@"the date is %@",yourDate);
    }

1) take out today's and yesterday's date , then compare the the date you enter and print accordingly

Kasaname
  • 1,491
  • 11
  • 15
0
NSTimeInterval interval = [dict[@"deviceTimeStamp"]doubleValue]; // set your intervals
NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval]; // set your past date or create it using dateWithIntervalSince1970 method
[formatter setDateFormat:@"hh:mm a"];
NSTimeZone *tz = [NSTimeZone defaultTimeZone];
NSInteger seconds = [tz secondsFromGMTForDate: date];
NSDate *dateee =  [NSDate dateWithTimeInterval: seconds sinceDate: date];
NSDateComponents *components = [[NSCalendar currentCalendar] components:units fromDate:dateee toDate:[NSDate date] options:0];
    if (components.day > 0)
    {
        if (components.day > 1){
            [formatter setDateFormat:@"MMM dd"];
            NSString *dateString = [formatter stringFromDate:date];
            NSlog(@"%@",dateString);
        }
        else{
                NSlog(@"Yesterday");
        }
   }
   else{
                NSlog(@"Today");
   }
Gurjinder Singh
  • 9,221
  • 1
  • 66
  • 58