1

如果这段代码在一个空的 Cocoa 应用程序中执行:

NSLog([[NSDate distantPast] isEqualToDate:[NSDate dateWithString:[[NSDate distantPast] description]]] ? @"YES" : @"NO");

我得到NO了结果。

考虑到 NSDate 已经存在了多长时间,我不认为它是一个错误,但它看起来有点奇怪,因为[NSDate dateWithString:@"0001-01-01 00:00:00 +0000"]实际上返回了0001-01-03 00:00:00 +0000

这是怎么回事?

4

1 回答 1

2

罪魁祸首是-[NSDate dateWithString:]。从 10.7 开始,它已被弃用。

@interface NSDate (NSCalendarDateExtras)
/*    DEPRECATED DEPRECATED DEPRECATED
 *    These methods are deprecated.
 *    Use NSCalendar for calendrical calculations.
 *    Use NSDateFormatter for date<->string conversions.
 */
...
+ (id)dateWithString:(NSString *)aString;
...
@end

这种方法一直存在问题,从不推荐用于日期解析。NSDateFormatter 允许更好地控制解析。

于 2012-06-21T03:35:18.473 回答