1

I have XML with this value:

<LastModifiedOnDate>2011-04-02T00:00:00</LastModifiedOnDate>

I am trying to parse this on iPhone from NSString to NSDate but have no luck.

NSDateFormatter *formate = [[[NSDateFormatter alloc] init] autorelease];  
        [formate setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss"];  
        //NSString *strConcat = @"2010-09-24 17:30:00";  
        NSDate *date = [formate dateFromString:string];
1110
  • 7,829
  • 55
  • 176
  • 334

3 Answers3

4

You don't need all those apostrophes in your format string. The only ones you need are around the T.

NSDateFormatter *formate = [[[NSDateFormatter alloc] init] autorelease];  
[formate setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
// I recommend setting a timezone because it will use the system timezone and that
// can cause confusion with your data.  
// [formate setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSString *strConcat = @"2010-09-24T17:30:00";  
NSDate *date = [formate dateFromString:strConcat];
NSLog(@"Date: %@", date);  // remember NSDate default to current timezone when logging to console

If you string have fraction of seconds, then add SSS to your string format: [formate setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];

For additional information on date formatting check out Unicode Technical Standard #35.

Black Frog
  • 11,595
  • 1
  • 35
  • 66
  • It's work, but have one more problem. When HH:mm:ss is 00:00:00 conversion doesn't work, I got null? – 1110 Apr 05 '11 at 12:22
  • you can do replacement on your string "00:00:00" with "00:00:00.000" so it will always have the fraction. – Black Frog Apr 05 '11 at 12:26
1

Replace your's SetDataFormat function with below and let me know for the result ...

    [formate setDateFormat:@"yyyy-MM-ddTHH:mm:ss"];
Jhaliya - Praveen Sharma
  • 31,697
  • 9
  • 72
  • 76
1
NSString *string=@"2011-04-05T12:43:56.537";
NSDateFormatter *formate = [[[NSDateFormatter alloc] init] autorelease];  
[formate setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS"];  
NSDate *date = [formate dateFromString:string];

its working..

Rakesh Bhatt
  • 4,606
  • 3
  • 25
  • 38
  • Sorry I didn't paste whole data. This is value from XML it has '.537' for seconds and thats not work because of that extension. 2011-04-05T12:43:56.537 – 1110 Apr 05 '11 at 12:05