【发布时间】:2018-02-01 00:06:03
【问题描述】:
我正在尝试检查两个日期是否相隔 1 个月。我读到我应该从NSCalendar使用这种方法components:fromDate:toDate:options:
我的代码
#define FORMAT_DATE_TIME @"dd-MM-yyyy HH:mm"
NSDate *updateDate = [Utils getDateFromString:airport.updateOn withFormat:FORMAT_DATE_TIME];
NSDate *now = [NSDate date];
NSString *nowString = [Utils getStringFromDate:now withFormat:FORMAT_DATE_TIME];
now = [Utils getDateFromString:nowString withFormat:FORMAT_DATE_TIME];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comps = [calendar components:NSCalendarUnitMonth fromDate:updateDate toDate:now options:0];
NSLog(@"%ld", (long)[comps year]);
NSLog(@"%ld", (long)[comps month]);
NSLog(@"%ld", (long)[comps day]);
这些是日志:
(lldb) 年份:9223372036854775807
(lldb) 月:0
(lldb) 日:9223372036854775807
(lldb) 现在 2017-08-23 11:54:00 +0000 发布
(lldb) po updateDate 2017-08-23 11:48:00 +0000
不应该所有的值都为零吗?
【问题讨论】:
-
我认为这是默认的“未设置”值(相当于 2^63-1)。如果您打印
NSDateComponents可能不会打印年份和日期,因为您没有在components:fromDate:toDate:options:中要求它。 -
您不需要将日期转换为字符串。
-
不,他们不应该。它只是未初始化的变量,其中的值是不可预测的,不应该被引用。
标签: objective-c nsdate nscalendar nsdatecomponents