私はObjective-cの初心者で、このクレイジーな問題が発生しました…</ p>
低精度テストケースの場合:
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];
}
どんな助けでも大歓迎です!!