Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString to NSDate

I got a string that contains the current date by using this :

NSString *date = [[NSDate date] description]; 

At a different point I want to retrieve the date from this string and I used the following code:

[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; //[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehaviorDefault]; [dateFormatter setDateFormat:@"YYYY-MM-DD HH:MM:SS ±HHMM"];  NSDate *dateFromString = [[NSDate alloc] init]; dateFromString = [dateFormatter dateFromString:<NSString containing date>]; 

I am getting dateFromString as nil 0x0. What am I doing wrong?

like image 294
Minar Avatar asked Aug 30 '09 04:08

Minar


1 Answers

You can't invent format string syntax and expect it to work; you need to actually use a documented format. (Seriously, "MM" meaning "month", "minute" and "GMT offset minutes" all at the same time?)

As the documentation points out, the 10.4 formatters use Unicode format strings.

Try "yyyy-MM-dd HH:mm:ss ZZZ" instead.

Also, Objective-C source is ASCII. Don't put characters like ± in there and expect it to work in any context; instead, use strings files.

like image 128
Nicholas Riley Avatar answered Sep 18 '22 19:09

Nicholas Riley