Search code examples
objective-cnsdatenscalendarnsdatecomponents

Check if two dates are one month apart


I'm trying to check if two dates are 1 month apart. I read that I should use this method components:fromDate:toDate:options: from NSCalendar

My code

#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]);

These are the logs:

(lldb) Year: 9223372036854775807

(lldb) Month: 0

(lldb) Day: 9223372036854775807

(lldb) po now 2017-08-23 11:54:00 +0000

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

Shouldn't all the value be zero?


Solution

  • The below line does not include the Year (NSCalendarUnitYear) and Day (NSCalendarUnitDay) component, only Month (NSCalendarUnitMonth) component is included.

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

    Add NSCalendarUnitYear and NSCalendarUnitDay to get [comps year] & [comps day] as 0.

    Like this :

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