Atilla Jax
Atilla Jax

Reputation: 615

NSDateComponents : Find older than 30 days

Using NSDateComponents I want to compare a departure date with now to see whether the departure date is > 30 days.

I use the NSDateComponents feature but in debugging it, its always like a really big number when I expect it to be 3 days, or 15 days or whatever.

   NSDate* now = [NSDate date];

    NSUInteger unitFlags = NSDayCalendarUnit;
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [calendar components:unitFlags fromDate:departureDate toDate:now options:0];

    NSInteger age = [components day]+1;

When I try to log the age

NSLog(@"age (in days) = %lu", (long) age);

it returns a really long number like 18446744073709551613

I would like to do an if statement that says;

if (age > 30) but am unsure of how to do this when the age being returned is a long number like this.

Many thanks

Upvotes: 0

Views: 530

Answers (2)

Verdant
Verdant

Reputation: 288

NSDate* date30 = [NSDate date];
date30 = [date dateByAddingInterval:86400*30]; 

if([departureDate compare:date30] == NSOrderedDescending){
    //Departure > Today + 30d
}    
else
{
    //Departure < Today + 30d
}

Is it what you need?

Upvotes: 1

Mohamed Jaleel Nazir
Mohamed Jaleel Nazir

Reputation: 5831

NSDate * dateNotFormatted = [NSDate date];
double now = [dateNotFormatted timeIntervalSince1970];
NSLog(@"%f",now);

NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate * dateDepareture =[dateFormatter dateFromString:@"29-06-2015"];
double dateDept = [dateDepareture timeIntervalSince1970];
NSLog(@"%f",dateDept);

Check the doublevalue for 30 days...

OR

NSDateComponents *components;
NSInteger days;

components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay fromDate:[NSDate date] toDate:[dateFormatter dateFromString:@"2-07-2015"] options:0];
days = [components day];
NSLog(@"%ld",(long)days);

Change the code to your need check for 30 days...

NSDayCalendarUnit NS_CALENDAR_ENUM_DEPRECATED(10_4, 10_10, 2_0, 8_0, "Use NSCalendarUnitDay instead") = NSCalendarUnitDay

Upvotes: 1

Related Questions