-1

I am trying to convert the duration between two dates to the format "'P'yyyy'Y'M'M'd'DT'H'H'm'M's.S'S'". An example of my expected output is: P0Y0M0DT0H0M0.002S (this is port of an Android project that uses DurationFormatUtils).

My test case:

NSDateIntervalFormatter *durationFormatter = [NSDateIntervalFormatter durationFormatter];
NSDate *date = [NSDate date];
NSDate *end = [date dateByAddingTimeInterval:25];
NSString *duration = [durationFormatter stringFromDate:date toDate:end];
XCTAssertTrue( [duration hasPrefix:@"P"], @"Actual String: %@", duration );

My formatter is defined as:

+ (NSDateIntervalFormatter*) durationFormatter {
    static NSDateIntervalFormatter *formatter = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        formatter = [[NSDateIntervalFormatter alloc] init];
        formatter.dateTemplate = @"'P'yyyy'Y'M'M'd'DT'H'H'm'M's.S'S'";
    });

    return formatter;
}

When I run this, duration is 3/5/2015, 16:46:20.3. If I set the locale on the formatter to nil and set the date and time format to NSDateIntervalFormatterFullStyle, the duration has the following format: Thursday, March 5, 2015, 4:51:36 PM GMT-05:00 - Thursday, March 5, 2015, 4:52:01 PM GMT-05:00.

How can I format the duration between two dates with ISO8601 period format (or at least as "'P'yyyy'Y'M'M'd'DT'H'H'm'M's.S'S'")?

Mike D
  • 4,938
  • 6
  • 43
  • 99
  • It would help if you told us what the inputs are!!! – Hot Licks Mar 05 '15 at 22:22
  • But I don't think that NSDateIntervalFormatter does what you want it to do. "A date interval is defined by two dates, for example, Sept 1st, 2013 - Oct 1st, 2013." – Hot Licks Mar 05 '15 at 22:29

2 Answers2

1

The class you are using, NSDateIntervalFormatter, is designed to produce intervals of the form date1 - date2, not format the time difference between two dates.

To get what you are after you need to use NSCalendar, NSDateComponents and stringWithFormat: (or similar).

  • First you need a calendar, [NSCalendar currentCalendar] is a good choice. (The difference between two absolute points in times can be a different when expressed in the units of a particular calendar - if that doesn't make sense don't worry, just use currentCalendar!)

  • Next use the components:fromDate:toDate:options: method to obtain an instance of NSDateComponents which contains the number of years, days, hours etc. between your two dates.

  • Finally use stringWithFormat: to format the components as you wish.

HTH

CRD
  • 52,522
  • 5
  • 70
  • 86
1

You have misunderstood what NSDateIntervalFormatter is for. It's for formatting an interval as a string of the form start - end.

It's not for formatting a duration.

You can use NSDateComponentsFormatter to format a duration. However, I don't know if it supports the specific format you want.

It has the convenience methods -stringFromDate:toDate: and -stringFromTimeInterval:.

Ken Thomases
  • 88,520
  • 7
  • 116
  • 154