Mark C
Mark C

Reputation: 33

Parse a .net datetime string into a NSDate object in objective C

I have a string that contains a .net datetime (rawData) and I am trying to parse it into a NSDate object using a NSDateFormatter. I think my format string might be wrong or something because the dateFromString: method is returning nil. Can any one please help me figure out the issue here?

NSString *rawData = @"2009-10-20T06:01:00-07:00";
//Strip the colon out of the time zone
NSRange timezone = NSMakeRange([data length] - 3, 3);
NSString *cleanData = [rawData stringByReplacingOccurrencesOfString:@":" withString:@"" options:NSCaseInsensitiveSearch range:timezone ];

//Setup a formatter and parse it into a NSDate object
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-ddThh:mm:ssZ"];
NSDate *result = [df dateFromString: cleanData]; //Result is nil

Upvotes: 2

Views: 1788

Answers (4)

Anupdas
Anupdas

Reputation: 10201

With iOS 6.0 and higher, representation for timezone with colon separating hour and minutes is added.(ZZZZZ or fallback z)Refer the following link Date Formats

This makes the code very simple

NSString *dateString = @"2009-10-20T06:01:00-07:00";
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
NSDate *date = [dateFormatter dateFromString:dateString];
NSLog(@"%@",date);

Upvotes: 3

Black Frog
Black Frog

Reputation: 11713

I just tested this code and it's work:

NSString *rawData = @"2009-10-20 06:01:00-07:00";
//Strip the colon out of the time zone
NSRange timezone = NSMakeRange([rawData length] - 3, 3);
NSString *cleanData = [rawData stringByReplacingOccurrencesOfString:@":" withString:@"" options:NSCaseInsensitiveSearch range:timezone ];
// Get rid of the T also
cleanData = [cleanData stringByReplacingOccurrencesOfString:@"T" withString:@" "];

//Setup a formatter and parse it into a NSDate object
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ssZZZ"];
NSDate *result = [df dateFromString: cleanData]; //Result is ni
NSLog(@"Result %@", result);

Couple of notes

  1. Get rid of the T.
  2. 24-Hour format for hours is HH

Upvotes: 0

Marc Charbonneau
Marc Charbonneau

Reputation: 40517

Looks like .NET outputs dates as ISO 8601 strings? For parsing these I use an open source NSFormatter subclass written by Peter Hosey, which you can find here. Unfortunately it's not trivial to parse these correctly using a simple dateFormat string. See also this question.

Upvotes: 0

Zaky German
Zaky German

Reputation: 14334

Try this:

    NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
    df.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SS";
    df.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"] autorelease];
    NSDate *result = [df dateFromString:rawData];

Upvotes: 0

Related Questions