Correct way to convert NSString to NSDate on iOS?

I used this method to convert a regular NSString to an NSDate, but tried to send an update to Apple and it was refused. What else way to do it in iOS?

NSString *date_str = @"2011-08-12T12:20:00Z"; NSDate *the_date = [NSDate dateWithNaturalLanguageString:date_str locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]]; 

Thanks in advance!

+3
source share
1 answer

Use NSDateFormatter . The following is a brief example:

 ... NSString* dateString = "2011-08-12T12:20:00Z"; NSDateFormatter* fmt = [NSDateFormatter new]; [fmt setDateFormat:"yyyy-MM-dd'T'HH:mm:ss'Z'"]; NSDate* date = [fmt dateFromString:dateString]; [fmt release]; ... 

Note that according to Unicode Technical Standard # 35 , NSDateFormatter does not support single-letter time zone identifiers (i.e. Z for zulu time).

+9
source

All Articles