开发者

dateFromString returns nil on iOS 4.2, works fine on 3.2!

开发者 https://www.devze.com 2023-02-04 21:48 出处:网络
I am converting a string returned from server to NSDate object for further use. Here is the sample string from server: 2011-01-14T16:05:48.555+05:00

I am converting a string returned from server to NSDate object for further use.

Here is the sample string from server: 2011-01-14T16:05:48.555+05:00

And, I use [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];

I am able to successfully convert it to an NSDate object using dataFromString method on iOS 3.2 (device & sim both).

However, the same code returns nil on iOS 4.2 on device & sim both.

I have also tried many variations of date format patterns such as:

[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ"];
[dat开发者_如何学PythoneFormatter setDateFormat:@"YYY-MM-DD'T'HH:mm:ss.fffK"];

but nothing works!!

Am I missing something here?

EDIT: I tried to hard-code the input string and after trying many variations, the following string 2011-01-14T16:05:48.555+0500 worked with "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

Notice that the only difference in this string and the one from server is; the colon (:) in TimeZone value. I tried to find a date pattern where I can mention the colon in timezone with no success.

Any clue??


I don't know the right answer on your question, but you may try this solution:

You can manually delete colon(:) in timeZone value in the string returned by server and write this string to new, and then use "yyyy-MM-dd'T'HH:mm:ss.SSSZ".

Source code:

NSString *stringFromServer=@"2011-01-14T16:05:48.555+05:00";

NSString *str1 = [stringFromServer substringToIndex:26];

NSString *str2 = [stringFromServer substringFromIndex:27];

NSString *result=[NSString stringWithFormat:@"%@%@",str1,str2];

so if this works:

EDIT: I tried to hard-code the input string and after trying many variations, the following string 2011-01-14T16:05:48.555+0500 worked with "yyyy-MM-dd'T'HH:mm:ss.SSSZ" Blockquote

then string "result" will work with "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

0

精彩评论

暂无评论...
验证码 换一张
取 消