0

I'm trying to display difference of 2 date in readable format. As you can see from my below code there are a lot of if-else closures. Is there any kind of formatter or my way of if-elses is right?

NSCalendar *c = [NSCalendar currentCalendar];
NSDateComponents *components = [c components:(NSCalendarUnitMonth | NSCalendarUnitDay)
                                        fromDate:startDate
                                          toDate:endDate
                                         options:0];

NSString *leftTimeStr = @"";
if (components.month == 0) {
    if (components.day == 1) {
        leftTimeStr = @"after 1 day";
    }
    else if (components.day > 1) {
        leftTimeStr = [NSString stringWithFormat:@"after %ld days", (long)components.day];
    }
}
else if (components.month == 1) {
    if (components.day == 0) {
        leftTimeStr = @"after 1 month";
    }
    else if (components.day == 1) {
        leftTimeStr = @"after 1 month 1 day";
    }
    else if (components.day > 1) {
        leftTimeStr = [NSString stringWithFormat:@"after 1 month %ld days", (long)components.day];
    }
}
else if (components.month > 1) {
    if (components.day == 0) {
        leftTimeStr = [NSString stringWithFormat:@"after %ld months", (long)components.month];
    }
    else if (components.day == 1) {
        leftTimeStr = [NSString stringWithFormat:@"after %ld months 1 day", (long)components.month];
    }
    else if (components.day > 1) {
        leftTimeStr = [NSString stringWithFormat:@"after %ld months %ld days", (long)components.month, (long)components.day];
    }
}

Resulting leftTimeStr string should be like one of the belows:

"after 5 months 22 days",
"after 5 months 1 day",
"after 5 months",
"after 1 month 22 days",
...
"after 22 days",
"after 1 day"
Shamsiddin Saidov
  • 2,281
  • 4
  • 23
  • 35

3 Answers3

2

For that you can use NSDateComponentsFormatter.

NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
[formatter setAllowedUnits:NSCalendarUnitMonth | NSCalendarUnitDay];
formatter.maximumUnitCount = 2;
formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleFull;
NSString *difference = [formatter stringFromDate:startDate toDate:endDate];
Nirav D
  • 71,513
  • 12
  • 161
  • 183
1

Use following category class of NSDate.

NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:0];
NSString *ago = [date timeAgo];
NSLog(@"Output is: \"%@\"", ago);
2011-11-12 17:19:25.608 Proj[0:0] Output is: "41 years ago"

Source from GitHub

Yurets
  • 3,999
  • 17
  • 54
  • 74
KKRocks
  • 8,222
  • 1
  • 18
  • 84
1

You can use NSDateComponentsFormatter with the SpellOut unit style which can output something like: "One hour, ten minutes".

Check here for details: http://nshipster.com/nsformatter/#nsdatecomponentsformatter

Omar AlEisa
  • 174
  • 8