【问题标题】:iOS After NSDateFormatter Date is nil [duplicate]NSDateFormatter之后的iOS日期为零[重复]
【发布时间】:2023-04-01 00:26:01
【问题描述】:

我的日期格式化程序有问题。我想比较两个日期,但是在我将两个日期都设置为相同格式后,日期为零。

compareDateNowString = 2014-05-24 19:03:39 +0000
compareDateFininshString = 2014-05-24 18:30:24 +0000 

    NSDateFormatter *compareFormatter = [[NSDateFormatter alloc]init ];
[compareFormatter setDateFormat:@"dd-MM-yyyy HH.mm"];

NSString *compareDateNowString = [NSString stringWithFormat:@"%@", [NSDate date]];
NSDate *compareDateNow = [compareFormatter dateFromString:compareDateNowString];
NSString *compareDateFinishString = [NSString stringWithFormat:@"%@", [device valueForKey:@"finishDate"]];
NSDate *compareDateFinish = [compareFormatter dateFromString:compareDateFinishString];

NSComparisonResult result = [compareDateNow compare:compareDateFinish];

if(result==NSOrderedAscending)
{
    cell.backgroundColor = [UIColor colorWithRed:0.0 green:255.0 blue:0.0 alpha:0.5];
}
else if(result==NSOrderedDescending)
{
    cell.backgroundColor = [UIColor colorWithRed:255.0 green:0.0 blue:0.0 alpha:0.5];
}
else
{
        NSLog(@"Both dates are the same");
}

【问题讨论】:

    标签: ios objective-c nsdateformatter null


    【解决方案1】:

    请改用@"yyyy-MM-dd HH:mm:ss Z"dateFormat 字符串。您的 dateFormat 与您尝试转换的字符串的格式不匹配。

    顺便说一句,将[NSDate date] 转换为字符串然后再转换回来是没有意义的。只需使用[NSDate date] 就可以了:

    NSDate *compareDateNow = [NSDate date];
    NSComparisonResult result = [compareDateNow compare:compareDateFinish];
    

    [device valueForKey:@"finishDate"] 可能也是如此。如果这已经是一个 NSDate 对象,只需使用它并完全绕过格式化程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-11
      • 1970-01-01
      • 1970-01-01
      • 2016-07-05
      • 2012-07-01
      • 2014-02-22
      相关资源
      最近更新 更多