When you create new date using [NSDate date] (i.e. today, as in right now) your date will save the current time as well as its date.
In fact, under the hood an NSDate object is the amount of seconds that have elapsed since the 1st of January 2001 (or 1970), in milliseconds. So really it’s a massive floating point number. You can see what it is with this code:
To save you the trouble, it’s bee roughly 1362585768.752258 seconds since 1970. But I digress…
Sometimes you want the date objects you’re dealing with not to regard “time” and really only deal with dates. As such, all dates – to be comparable – need to have the very same time, say midnight. Otherwise you may get the wrong results. Imagine adding three date objects that each have noon as their time, that’s an extra day and a half clouding your results right there.
Here’s some code that will normalize your NSDate object by setting its time to midnight:
Imagine you had two NSDate objects and you’d like to find out the time interval between those dates. NSDate objects alone won’t help us out there unless we do some serious NSDateFormatting and hair pulling.
Lucky for us there are a few other classes available that will help us do this, namely NSCalendar and NSDateComponents.
Years, Months and Days
Here’s how you can determine how many years, months and days have passed between two NSDates:
The above example returns Years: 12, Months: 2, Days: 5.
In a nutshell we split the date into “components” such as years, months and days, and let the NSDateComponents class give us those as NSIntegers (i.e. long integers). For the class to calculate this correctly we need to put our days into the context of an NSCalendar (gregorian in our case). This is important because different calendars may return different time intervals.
Just the Days
If you’re interested in just one particular item (days for example) just leave out any other component on this line:
// just the days
How about other units?
You can pass as many of those fast enumeration units as you like, separated by pipes. For a full list of available values check out the NSCalendar Class Reference
First we’ll create a date object. Next we’ll create an NSDateFormatter and set how we’d like for display our date (and optionally our time). Then we’ll call the magical stringFromDate method which will create our string.