Mangesh
Mangesh

Reputation: 2285

Need to convert NSString to Nsdate

I need to convert "2013-05-05T00:00:00Z" this string to NSDate and again NSDate to Nsstring. I have tried with different-differnt format style but didn't get any success.

I have already checked.

NSDate from NSString

Convert NSDate to Sql Server Datetime format

Thanks.

// for getting string for Advance search  

-(NSDate*) doGetDateFromStringGSearch :(NSString*) dateStr 
{

NSDateFormatter * outputFormatter4 = [[[NSDateFormatter alloc ] init ] autorelease ];

NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[outputFormatter4 setLocale:locale];

//[outputFormatter4 setDateFormat: @"yyyy-MM-dd'T'HH:mm:ss:SSS"];
//[outputFormatter4 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"];
 [ outputFormatter4 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss:Z" ];
 //[ outputFormatter4 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss':00Z'" ];

NSString * inputString2 = dateStr;
NSDate * inputRecivedToDate = [outputFormatter4 dateFromString:inputString2 ];
NSLog(@"doGetDateFromString  %@", inputRecivedToDate);

return [[inputRecivedToDate retain] autorelease];
}

Upvotes: 0

Views: 1496

Answers (2)

Anoop Vaidya
Anoop Vaidya

Reputation: 46543

Change you formatter string to :

[outputFormatter4 setDateFormat:@"yyyy-MM-dd'T'hh:mm:ss'Z'"];

The full code:

NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'hh:mm:ss'Z'"];
NSDate *date=[dateFormatter dateFromString:@"2013-05-05T00:00:00Z"];

NSLog(@"%@",date);

Upvotes: 3

Miroslav Kovac
Miroslav Kovac

Reputation: 1208

I have been using the NSDateFormatter with @"yyyy-MM-dd'T'HH:mm:ssZZZZ" format for many years, but found out that on few, but only few (maybe less then 1%) of devices it was unsuccessful and was returning nil.

So as a fallback I have been using this library: https://github.com/keithpitt/ISO8601DateFormatter and now I am not seeing any issues with parsing ISO8601 date formats.

The library supports both dateFromString: and stringFromDate:.

Upvotes: 1

Related Questions