NSDateFormatter返回两个不同的输入相同的格式?

问题描述:

我的Objective-C的新手,我得到这个疯狂的问题...NSDateFormatter返回两个不同的输入相同的格式?

用于低精度测试案例:

dateString = @ “2010-05-25 11点05分21秒”,转换成功。

dateString = @“2010-03-01 15:54:36”,转换失败。

高精度测试用例:

dateString = @ “2010-05-25 11:05:21.937113”,转换成功。

dateString = @“2010-03-01 15:54:36.937113”,转换失败。

下面

是我的代码:

// Date formatter 
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; 
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; 
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss.SSSSSS"]; 
[dateFormatter setLocale:locale]; 

NSDateFormatter *lowPrecisionDateFormatter = [[[NSDateFormatter alloc] init] autorelease]; 
[lowPrecisionDateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4]; 
[lowPrecisionDateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"]; 
[lowPrecisionDateFormatter setLocale:locale]; 

// try high precision first, if fail, then go ahead to low precision. 
NSDate *date = [dateFormatter dateFromString:dateString]; 
if(!date){ 
    date = [lowPrecisionDateFormatter dateFromString:dateString]; 
} 

任何帮助,高度赞赏!

这只是一个猜测,但我认为它与使用24小时日格式而不是AM和PM有关。我相信如果你在你的setDateFormat字符串中使用HH而不是hh,它应该可以工作。

编辑:

其实,我很有信心,这是它在寻找this blog posting后。

+0

感谢队友,隔夜工作真的让我失去了焦点! :( – sunnycmf 2010-05-26 02:17:39