0

我正在尝试从 2 个 NSStrings 创建一个 NSDate 对象。

其中一个 NSString 的格式为 ==> 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 语法中指示它的存在。我怎样才能做到这一点?

帮助表示赞赏,

帕春

4

1 回答 1

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];
}
于 2012-05-01T21:47:25.177 回答