【问题标题】:NSDate from 12 hour timeNSDate 从 12 小时开始
【发布时间】:2012-04-30 23:53:03
【问题描述】:

我正在尝试从 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 语法中指示它的存在。我该怎么做?

帮助感谢,

帕春

【问题讨论】:

    标签: nsdate nsdateformatter


    【解决方案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];
    }
    

    【讨论】:

      猜你喜欢
      • 2011-01-19
      • 1970-01-01
      • 2017-10-20
      • 1970-01-01
      • 1970-01-01
      • 2015-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多