Does anyone know of a library or something that will convert an NSDate into strings like the examples below?
1 hour ago
yesterday
last Thursday
2 days ago
last month
6 months ago
last year
Does anyone know of a library or something that will convert an NSDate into strings like the examples below?
1 hour ago
yesterday
last Thursday
2 days ago
last month
6 months ago
last year
For posterity, here's an NSDate category method I threw together that uses the Stack Overflow relativity calculation linked by David as well as other tips cobbled from other similar SO questions:
DateTools is an awesome comprehensive framework for doing all sorts of date related functions. https://github.com/MatthewYork/DateTools
As an NSDate category, it's easier to use than SORelativeDateTransformer.
However, there's an issue with getting accurate day values. (E.g. If today is Monday morning, Saturday evening will be reported as "Yesterday"; should be "Two days ago")
This should work better (using DateTools):
NSDateFormatter will do a great deal of what is mentioned above by using setDoesRelativeDateFormatting: on an instance. From there, you can control the formatting using the date style and the time style to fine tune it to your needs.
If that doesn't get you what you need then check out SORelativeDateTransformer, it is an NSValueTransformer subclass that attempts to provide the same behavior you see with relative dates on SO.
Finally, if you want to roll your own or do more research here is the (likely) original question on the topic... yes it is question 11.
DO NOT use your own custom string translation. Writing your own translation that does something like "3 seconds ago" not only has the problem of needing to be updated constantly, but it also does not localize into other languages.
Instead, use Apple's built in NSDateFormatter:
This will output something like "Today, 11:10 PM", or "7/17/14, 5:44 AM".
It appears that TTTTimeIntervalFormatter in FormatterKit can also help with generating relative time interval strings.