Quote:
Originally Posted by lexy0202
Hi There,
Was wondering if anyone knew of a class which would give you a string telling you in 'human terms' how long ago a date was. For example on twitter/facebook when you see post dates like 2 minutes ago, or 3 hours ago, or 2 days ago... anyone know of a class which handles all the cases like this... or else how do I basically go about doing something like that with an NSDate??
Thanks in advance,
Alex
|
There's no single class to do this, but there are tools that make it fairly straightforward.
You need an NSCalendar object to define the calendar you're using. Most Western countries use the Gregorian calendar, so you probably want to create a gregorian calendar.
You could use the NSCalendar method components:fromDate:toDate

ptions. That will let you calculate a difference between dates using units you specify. The answer comes back and an NSDateComponents object, which gives you numbers of years, months, weeks, days, etc. You tell the components:fromDate:toDate

ptions method which units you want, and it calculates the answer in those units. There are then NSCalendar methods to convert NSDateComponents component values (months, days, years) to their string equivalents.
See the XCode docs on NSCalendar, NSDateComponents, and NSDate for more information. Its pretty well documented, and quite rich.
Edit: Make sure you search on "Calendrical Calculations" and read that whole chapter, and in particular the section titled "Temporal Differences". That section includes sample code that does almost exactly what you want.