I have a NSTimeInterval calculated from two NSDate objects. How do I return the year value of this interval as a double or CGFloat with multiple decimal digits?
Let's say, I have someone's dob and I wanna return his age as a decimal like xx.xxxxxxxx years old.
You need to use NSCalendar. And make the difference with the NSDate objects. Here is an example:
// The time interval
NSTimeInterval theTimeInterval = ...;
// Get the system calendar
NSCalendar *sysCalendar = [NSCalendar currentCalendar];
// Create the NSDates
NSDate *date1 = [[NSDate alloc] init];
NSDate *date2 = [[NSDate alloc] initWithTimeInterval:theTimeInterval sinceDate:date1];
// Get conversion to months, days, hours, minutes
NSCalendarUnit unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *breakdownInfo = [sysCalendar components:unitFlags fromDate:date1 toDate:date2 options:0];
NSLog(@"Break down: %i min : %i hours : %i days : %i months", [breakdownInfo minute], [breakdownInfo hour], [breakdownInfo day], [breakdownInfo month]);
Since NSTimeInterval specifies the number of seconds, all you need to do to get an approximation* is dividing by the number of seconds in a year:
#define SEC_PER_YEAR (365*24*60*60)
...
NSTimeInterval diff = ...
double diffYear = ((double)diff)/SEC_PER_YEAR;
* This number would not be exact, because the number of seconds per year changes depending on the year.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With