views:

4632

answers:

4
+2  Q: 

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 am want to retrieve the date from this string and I use 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 I am doing wrong?

+8  A: 

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.

Nicholas Riley
Works just fine
Minar
+1  A: 

Now that the NSDateFormatter's init function is deprecated in iPhone OS 4, what other solution would you suggest?

In MAC OS X apparantly there is

-(id) initWithDateFormat:(NSString *)dateFormat allowNaturalLanguage:(BOOL)flag;

but unfortunately there is no other init method for iPhone OS ... :-(

Any ideas?

Thank you.

Sasho
A: 

@sasho you don't need to init with anything special - if you look at the example the O.P. (original poster) used he set the format after init'ing the NSDateFormatter. I'm not sure what you meant by "init function is deprecated in iPhone OS 4" you can't really deprecate the init function of an object.

btw for those wondering why i posted this as an answer - i guess you can't comment until you have enough reputation? not sure what people are supposed to do until then - other than use the system incorrectly.

Sebastian Bean
Here is what I mean:http://stackoverflow.com/questions/3182314/nsdateformatters-init-method-is-deprecatedSorry for the delay, but I have not visited this post last few months.
Sasho
A: 

Also, dateFromString: returns an autoreleased NSDate, so:

NSDate *dateFromString = [[NSDate alloc] init]; // <- non freed instance
dateFromString = [dateFormatter dateFromString:<NSString containing date>]; // <- new autoreleased instance
....
[dateFromString release]; // <- wrong

You may want to:

//NSDate *dateFromString = [[NSDate alloc] init];
NSDate *dateFromString = [dateFormatter dateFromString:<NSString containing date>];
....
//[dateFromString release]; // dateFromString is autoreleased

Hope this could save someone :)

grilix