2

What format string do I need to use to parse the string value of "2012-03-07T21:08:23.6875-05:00" into an NSDate?

Background:

I'm using Sudzc ARC against a .NET web service. The web method is return two .NET DateTime properties. Although both are .NET DateTime properties, the web method is returning them in different date/time formats.

The first DateTime's value is set within SQL Server and returns a value in this format "2012-03-07T21:08:23". Sudzc parses this great...no problems yet.

The second DateTime's value is set by .NET as DateTime.Now.AddHours(24). The web method returns that as a value of "2012-03-07T21:08:23.6875-05:00" which contains the additional milliseconds and timezone offset (ex: ".6875-05:00"). Sudzc will not parse this value into an NSDate, and the soap.m method dateFromString returns a value of nil.

I'm pretty sure this has to do with the NSDateFormater. soap.m comes with the below...

+ (NSDateFormatter*)dateFormatter {
static NSDateFormatter* formatter;
if(formatter == nil) {
    formatter = [[NSDateFormatter alloc] init];
    NSLocale* enUS = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [formatter setLocale: enUS];
    [formatter setLenient: YES];
    [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
}
return formatter;
}

// Converts a string to a date.
+ (NSDate*) dateFromString: (NSString*) value {
if([value rangeOfString:@"T"].length != 1) {
    value = [NSString stringWithFormat:@"%@T00:00:00.000", value];
}
if([value rangeOfString:@"."].length != 1) {
    value = [NSString stringWithFormat:@"%@.000", value];
}
if(value == nil || [value isEqualToString:@""]) { return nil; }

NSDate* outputDate = [[Soap dateFormatter] dateFromString: value];
return outputDate;
}

I've attempted to modify the format string from "yyyy-MM-dd'T'HH:mm:ss.SSS" to "yyyy-MM-dd'T'HH:mm:ss.SSSSSS-zz:zz" and other variants, but NSDate always comes back as nil.

Erik Olson
  • 5,807
  • 1
  • 18
  • 17
  • NSDateFormatter can't handle the ":" in the timezone piece. You must remove that ":" before parsing with NSDateFormatter. – Hot Licks Mar 07 '12 at 02:27
  • 1
    It should be noted that with iOS6 there is now support for the ":" in the timezone. The full format would be "yyyy-MM-dd'T'HH:mm:ss.SSSSZZZZZ". – Hot Licks Oct 09 '13 at 11:34

1 Answers1

0

I use this to convert from a .NET web service with sudzc

https://github.com/boredzo/iso-8601-date-formatter

ISO8601DateFormatter *isoDateFormatter = [[ISO8601DateFormatter alloc] init];
[isoDateFormatter dateFromString: ... ]
Peter Hosey
  • 95,783
  • 15
  • 211
  • 370
maggix
  • 3,268
  • 1
  • 22
  • 36