You could convert each NSDate
value to an NSDateComponents
value using NSCalendar
's componentsInTimeZone:fromDate:
method. This will give you the year, month and day values for your two dates, now implement your difference algorithm, which might be:
- subtract the earlier date from the larger one - you can determine that based on comparing the two
NSDate
values
- the year difference is just simple subtraction of the year components of the
NSDateComponents
values
- the month difference is the difference between the month components, if this is negative add 12
- the day difference is similar but in the negative case you have to add the length of month, which is 28, 29, 30 or 31 - figuring which is left as an exercise :-) (
NSCalendar
/NSDate
Methods should help here)
While this guess at your required algorithm might be wrong, whatever your algorithm you should be able to implement it based on the year, month and day components. HTH
Update
So my first guess at your algorithm was wrong, my second guess is that your three differences; years, months, days; are all meant to be independent approximations of the difference in the corresponding unit. So the year difference ignores the months, days and time; the month difference ignores the days and time; and the days difference ignores the time. This is why 31 May and 1 June are "1 month" apart - the day is ignored. This guess may also be wrong of course but here is how to do it:
- order you two dates so the difference is going to be positive.
- get just the year, month and day components (or get them all and then discard the others) – this will discard the time component. Use one of
NSCalendar
's methods to do this.
- your year difference is just the difference between the year components
- your month difference is the difference between your month components (which could be negative) plus 12 times your year difference
- your day difference can be found using
components:fromDateComponents:toDateComponents:options:
requesting only the day component
[Note: be careful to use the same timezone as the original dates – this is a bit fiddly as you may need to extract it from the date strings yourself (extract the +hhmm and make a time zone). You must remember that an NSDate
does not store the time zone, its just an absolute point in time (so equivalent times in different times zones produce the same NSDate
value) and for your calculations you want them based on the original time zone as two times one the same day in one timezone can be on different days in a different time zone...). You can set the timezone of an NSCalendar
instance or use methods which take timezones when converting from NSDate
to NSDateComponents
]