For iPhone OS 4.0 “dateFromString” method of NSDateFormatter returns nil

纵然是瞬间 提交于 2019-12-03 12:58:00

问题


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 ?


回答1:


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




回答2:


[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];



回答3:


In iOS2.x and 3.x the NSDate description/datefromstring function returns: 2010-09-24 17:30:00 - 0700

in iOS 4.1 it returns this: 2010-09-25 00:30:00 GMT

You could submit a bug to apple. It doesn't even follow the specification which states that it should return 0000 for the offset. So not only does it not return local date, it also uses GMT instead of an offset. It appears that this new format isn't compatible with NSDateFormatter methods.

Also, I don't think it is an error in documentation. In the API Diff document, it lists that init is removed for NSDateFormatter.



来源:https://stackoverflow.com/questions/3212214/for-iphone-os-4-0-datefromstring-method-of-nsdateformatter-returns-nil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!