As Tom Harrington's answer notes, you can produce a colloquial representation of a moment or a time interval using NSDateComponentsFormatter
.
However, if you want to do exactly what the question asks in its example, which is to produce a colloquial representation of a moment in the past, relative to the present moment, like for a timeline-oriented UI, then it seems like NSDateComponentsFormatter
is not suitable. As the documentation for stringFromTimeInterval(_:)
says, the time interval value "must be a finite number. Negative numbers are treated as positive numbers when creating the string."
As near as I can tell, the best choice is TTTTimeIntervalFormatter
, a standalone class in Mattt Thompson's FormatterKit.
I have produced an Xcode 7 playground, RelativeDatePlayground, that compares the outputs of NSDateFormatter
output to TTTTimeIntervalFormatter
. Here is a table showing output for different relative times in seconds. As you can see, NSDateComponentsFormatter
does not seem to handle past moments or the present moment well:
-1488010 | 2 weeks ago | -1 week remaining
-1468800 | 2 weeks ago | -1 week remaining
-864000 | 1 week ago | 0 seconds remaining
-86400 | 1 day ago | -1 day remaining
-36000 | 10 hours ago | -10 hours remaining
-3600 | 1 hour ago | -1 hour remaining
-600 | 10 minutes ago | -10 minutes remaining
-60 | 1 minute ago | -1 minute remaining
-10 | 10 seconds ago | -10 seconds remaining
-1 | 1 second ago | -1 second remaining
-0 | just now | 0 seconds remaining
0 | just now | 0 seconds remaining
1 | 1 second from now | 1 second remaining
10 | 10 seconds from now | 10 seconds remaining
60 | 1 minute from now | 1 minute remaining
600 | 10 minutes from now | 10 minutes remaining
3600 | 1 hour from now | 1 hour remaining
36000 | 10 hours from now | 10 hours remaining
86400 | 1 day from now | 1 day remaining
864000 | 1 week from now | 1 week remaining
1468800 | 2 weeks from now | 2 weeks remaining
1488010 | 2 weeks from now | 2 weeks remaining