Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For iPhone OS 4.0 "dateFromString" method of NSDateFormatter returns nil

I am using following code & its working perfectly fine in iPhone OS 3.2

+(NSDate *)NSDateFromString:(NSString *)dateString
{

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateStyle:NSDateFormatterShortStyle];
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *dateObj=[dateFormatter dateFromString:dateString];
    [dateFormatter release], dateFormatter=nil;
    return dateObj;
}

But when I tried to use the same code I iPhone OS 4.0 the dateObj was nil.

The reason is :

- (id)init method for NSDateFormatter is only Available in iPhone OS 2.0 through iPhone OS 3.2. It is deprecated in iPhone OS 4.0.

Now what is the solution for that ? How to init NSDateFormater? What's the alternative ?

like image 334
Nic Avatar asked Jul 09 '10 11:07

Nic


2 Answers

- (id)init is not deprecated for NSDateFormatter in iOS4. That's an error in the documentation.

like image 85
Axel Avatar answered Sep 26 '22 00:09

Axel


[NSDateFormatter dateFormatFromTemplate:options:locale:] might work better

NSString *format = [NSDateFormatter
                   dateFormatFromTemplate:@"Mdjm"
                                  options:0
                                   locale:[NSLocale currentLocale]];

// "M/d h:mm a" // US English format returned for US locale

[dateFormatter setDateFormat:format];
NSDate *date = [dateFormatter dateFromString:dateString];
like image 33
Thom Mahoney Avatar answered Sep 24 '22 00:09

Thom Mahoney