-6

Possible Duplicate:
How can I calculate the difference between two dates?
NSDate, comparing two dates

I have got two dates. How to check if theres a difference of 30 days in between them? I actually have an In-App purchase which needs to be disabled after every 30-days of purchase. When the user buys the feature, the Date is saved and so I need to check the dates. If 30-days have passed, I need to disable the feature again.

Community
  • 1
  • 1
SHA
  • 15
  • 2
  • 6
  • 4
    Please learn to use the search function on Stack Overflow. This question has been asked many many times before. – Nick Bull Jul 12 '12 at 11:48
  • possible duplicate of [How can I calculate the difference between two dates?](http://stackoverflow.com/questions/4371757/how-can-i-calculate-the-difference-between-two-dates), [Number of days between two NSDates](http://stackoverflow.com/questions/4739483/number-of-days-between-two-nsdates) – jscs Jul 12 '12 at 16:49

3 Answers3

6

You can convert both dates to seconds with timeIntervalSince1970 and then check if difference is bigger than 2592000 (30*24*60*60 which is 30 days * 24 hours * 60 minutes * 60 seconds).

NSTimeInterval difference = [date1 timeIntervalSince1970] - [date2 timeIntervalSince1970];

if(difference >2592000)
{
 //do your stuff here
}

EDIT: For more compact version you can use - (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate

NSTimeInterval difference = [date1 timeIntervalSinceDate:date2];
if(difference >2592000)
{
    //do your stuff here
}
Michal
  • 961
  • 1
  • 12
  • 19
1

Provide the start and end NSDate in following manner:

    NSDate *date_Start;
    NSDate *date_End;
    NSCalendar *cal=[NSCalendar currentCalendar];
NSDateComponents *components=[cal components:NSDayCalendarUnit fromDate:date_Start toDate:date_End options:0];
    int days=[components day];
    if(days>30){
     //Your code here
    }
NNikN
  • 3,720
  • 6
  • 44
  • 86
-1

You could create a date which is +30days from now :

NSDate *thrityDaysPlus = [[NSDate date] dateByAddingTimeInterval:3600*24*30]

and then simply compare it to your saved date

if ([date1 compare:date2] == NSOrderedDescending) {
    NSLog(@"date1 is later than date2");        

} else if ([date1 compare:date2] == NSOrderedAscending) {
    NSLog(@"date1 is earlier than date2");

} else {
    NSLog(@"dates are the same");

}
Alexander
  • 7,178
  • 8
  • 45
  • 75