0

2 つの NSString から NSDate オブジェクトを作成しようとしています。

NSStrings の 1 つは ==> mm/dd/yyyy の形式です (次のサンプルでは g.date)。

もう 1 つは ==> 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

NSDateFormatter 構文でその存在を示す方法が見つからないため、時刻文字列の AM/PM 部分を切り捨てています。これどうやってするの?

助けていただければ幸いです。

パチュン

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 に答える