bruno
bruno

Reputation: 2169

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?

Upvotes: 1

Views: 327

Answers (2)

Deep Moradia
Deep Moradia

Reputation: 126

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

Upvotes: 2

Abdelahad Darwish
Abdelahad Darwish

Reputation: 6067

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

Upvotes: -1

Related Questions