Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get year difference between two NSDates with multiple decimal digits

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.

like image 579
Lixu Avatar asked Nov 18 '25 08:11

Lixu


2 Answers

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]);
like image 168
Joze Avatar answered Nov 19 '25 21:11

Joze


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.

like image 31
Sergey Kalinichenko Avatar answered Nov 19 '25 23:11

Sergey Kalinichenko