检查两个日期是否相隔一个月

时间:2017-08-23 11:55:47

标签: objective-c nsdate nscalendar nsdatecomponents

我试图检查两个日期是否相隔1个月。我读过我应该使用components:fromDate:toDate:options:

中的这种方法NSCalendar

我的代码

#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)po现在2017-08-23 11:54:00 +0000

     

(lldb)po updateDate 2017-08-23 11:48:00 +0000

不应该将所有值都归零吗?

2 个答案:

答案 0 :(得分:2)

以下行不包含年份(NSCalendarUnitYear)和日期(NSCalendarUnitDay)组件,仅包含月份(NSCalendarUnitMonth)组件。

NSDateComponents *components = [calendar components:NSCalendarUnitMonth fromDate:updateDate toDate:now options:0];

添加NSCalendarUnitYearNSCalendarUnitDay以获得[comps year]& [comps day]为0。

像这样:

NSDateComponents * components = [calendar components:NSCalendarUnitMonth |NSCalendarUnitYear|NSCalendarUnitDay fromDate:updateDate toDate:now options:0];

答案 1 :(得分:-1)

你可以用这个

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:FORMAT_DATE_TIME];
NSDate *updateDate  = [dateFormatter dateFromString:@"24-07-1990 15:20"];

NSDate *now = [NSDate date];


NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;


NSDateComponents *comps = [calendar components:unitFlags fromDate:updateDate toDate:now options:0];


NSLog(@"%ld", (long)[comps year]);
NSLog(@"%ld", (long)[comps month]);
NSLog(@"%ld", (long)[comps day]);