1

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?

bruno
  • 2,154
  • 5
  • 39
  • 64
  • 3
    I think it's the default "unset" value (equivalent to 2^63-1). If you print `NSDateComponents` is may not print the year and day because you didn't ask for it in `components:fromDate:toDate:options:`. – Larme Aug 23 '17 at 12:01
  • 1
    You don't need to convert the date to and from a string. – jscs Aug 23 '17 at 12:27
  • No, they shouldn't. It's just uninitialized variables, values in them are unpredictable and shouldn't be referred. – Cy-4AH Aug 23 '17 at 13:08

2 Answers2

2

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];
Deep Moradia
  • 126
  • 5
-1

you can use this

 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]);
Abdelahad Darwish
  • 5,969
  • 1
  • 17
  • 35