Xcode How to calculate the number of month between two dates
I would like to calculate the amount of month since the last time an app has been started.
To do this, I save the current date at viewdidload
to NSUserdefaults
as String.
Bef开发者_如何学Pythonore I save the current date, I have to calculate the difference in month between the old(saved) date and the current date.
I am new in programming with NSDates, can someone tell me how to do this? And how to print the count in a lable?
Hope you understand what I mean and also someone could help me...
regards Dennis
The preferred way is to use NSCalendar.
-(int)differenceInMonthsFrom:(NSDate*)older to:(NSDate*)younger {
NSCalendar *calendar=[NSCalendar currentCalendar];
NSDateComponents *components=[calendar components:NSMonthCalendarUnit fromDate:older toDate:younger options:0];
return [components month];
}
Note that this function does not check for ordering. Getting from your stored string to NSDate may be a trick; it might be wiser to store the date as an integer?
you have to use NSDate
objects. for example :
NSDate *now=[NSDate date]; // this is **now** date object
NSDate *lastSaved=[NSdate lastDate]; // this is last saved object
NSComparisonResult duration=[now timeIntervalSinceDate:lastSaved]; //this will return time interval between this 2 date object in seconds
hoursInterval=duration/3600; // this will return hours of interval between this 2 date
daysInterval=hoursInterval/24; // this will return days interval between this 2 date
monthsInterval=daysInterval/30; // and this will return month interval between this 2 date
精彩评论