开发者

dateFromString returns nil

This is my NSString,

myDate : 2011-06-07 11:23:47  0000

And this is the code,

NSTimeZone *currentDateTimeZone = [NSTimeZone defaultTimeZone];
NSDateFormatter *currentDateFormat = [[NSDateFormatter alloc]init];
[currentDateFormat setTimeZone:currentDateTimeZone];
[currentDateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];开发者_JS百科
NSDate *tempDate = [currentDateFormat dateFromString:second];

Still tempDate gets the value nil.

Can anyone help?


How did you get the date string? It needs to be 2011-06-07 11:23:47 +0000 for this to work.


Try this, This is the function to get Date from String .

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setFormatterBehavior:NSDateFormatterBehavior10_4];
[df setDateFormat:@"EEE, dd MMM yy HH:mm:ss"];
NSDate *convertedDate = [df dateFromString:stringDate];
[df release];
// [convertedDate description]
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setAMSymbol:@"AM"];
[formatter setPMSymbol:@"PM"];
[formatter setDateFormat:@"MM/dd/yyyy hh:mm:a"];
return [formatter stringFromDate:convertedDate];


What I think is, it not related to TimeZone but the device 24hours settings. Developer has to check if the device timings are of 24hours then they should use HH, and if the device timings are of 12hours then they should use hh.


NSTimeZone *currentDateTimeZone = [NSTimeZone defaultTimeZone];
NSDateFormatter *currentDateFormat = [[[NSDateFormatter alloc]init] *autorelease*];
[currentDateFormat setTimeZone:currentDateTimeZone];
[currentDateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss *ZZZZ*"];
NSDate *tempDate = [currentDateFormat dateFromString:second];

Add autorelease and ZZZZ insead of Z.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜