我正在尝试从2个NSStrings创建一个NSDate对象。
其中一个NSStrings的格式为==> mm / dd / yyyy(以下样本中的g.date)
另一种形式为==> hh:mm am / pm(以下样本中的g.time)
以下代码:
for(Game *g in _games) {
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"dd'/'MM'/'yyyy HH':'mm"];
NSString *dateString = [NSString stringWithFormat:@"%@ %@", g.date, g.time];
dateString = [dateString substringToIndex:[dateString length]-3];
NSDate *date = [format dateFromString:dateString];
NSLog(@"%@ ==> %@", dateString, date);
}
产生不准确和不可预测的输出,如下所示:
2012-04-30 19:39:06.923 MLP[27866:fb03] 05/03/2012 8:30 ==> 2012-03-05 13:30:00 +0000
2012-04-30 19:39:06.923 MLP[27866:fb03] 05/03/2012 8:45 ==> 2012-03-05 13:45:00 +0000
2012-04-30 19:39:06.924 MLP[27866:fb03] 03/29/2012 9:30 ==> (null)
2012-04-30 19:39:06.924 MLP[27866:fb03] 03/29/2012 8:15 ==> (null)
2012-04-30 19:39:06.925 MLP[27866:fb03] 03/01/2012 9:15 ==> 2012-01-03 14:15:00 +0000
2012-04-30 19:39:06.925 MLP[27866:fb03] 05/03/2012 9:00 ==> 2012-03-05 14:00:00 +0000
2012-04-30 19:39:06.926 MLP[27866:fb03] 03/29/2012 9:00 ==> (null)
2012-04-30 19:39:06.926 MLP[27866:fb03] 05/03/2012 9:15 ==> 2012-03-05 14:15:00 +0000
我正在切断时间字符串的AM / PM部分,因为我无法找到如何在NSDateFormatter语法中指示它的存在。我怎么能这样做?
帮助表示赞赏,
Pachun
答案 0 :(得分:1)
为未来可能遇到此问题的任何人解决这个问题。这就是修正它的原因:
// Sort by date
- (NSComparisonResult)compare:(Game *)g {
// Parse date's strings to an NSDate
NSDateFormatter *format = [NSDateFormatter new];
[format setDateFormat:@"MM/dd/yyyy hh:mma"];
NSString *otherDateString;
NSString *myDateString;
if([g.time length]==7)
otherDateString = [NSString stringWithFormat:@"%@ 0%@", g.date, g.time];
else otherDateString = [NSString stringWithFormat:@"%@ %@", g.date, g.time];
if([_time length]==7)
otherDateString = [NSString stringWithFormat:@"%@ 0%@", _date, _time];
else otherDateString = [NSString stringWithFormat:@"%@ %@", _date, _time];
NSDate *otherDate = [format dateFromString:otherDateString];
NSDate *myDate = [format dateFromString:myDateString];
return [myDate compare:otherDate];
}