将 NSString 转换为 NSDate 不起作用

Convert NSString to NSDate is not working

我使用与这个最佳答案相同的代码

Converting NSString to NSDate (and back again)

NSString *dateString = @"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter dateFromString:dateString];

但 dateFromString 结果是 2010-01-31 17:00:00 +0000 为什么不是同一天。
我无法比较日期。

这是因为你当前的时区,添加这个然后它会给你正确的日期

[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];

在您设置日期格式的位置后立即添加以下行。这是因为它将默认转换为设备的本地时区。对我有用!

[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];

实际上是同一个日期。但默认情况下,如果未传入时区,日期格式化程序会在设备的本地时区中解析日期字符串。在您的情况下,您的日期被解释为 2010 年 2 月 2 日午夜 UTC+7,即 2010 年 1 月 31 日 17:00 协调世界时。

如果日期字符串始终为 UTC,请将 UTC 时区传入日期格式化程序,如下所示:

NSString *dateString = @"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter dateFromString:dateString];