I am attempting to convert a UTC formatted date from an API to a human-readable approximation format using Swift.
I'm looking for something like the following:
2015-07-14T13:51:05.423Z
to
About two weeks ago
What is the best approach to this in Swift? While optimally this could format strings directly, I understand that this will probably require casting the string to a NSDate object.
Any help would be greatly appreciated.
EDIT: My question had been identified as a possible duplicate of another question. Tom's solution below is written for Swift and much more elegant than creating a new method in regards to my situation.
You need two steps. First, convert your date string to an
NSDate
:(If that's not an exact representation of the strings you get, you'll have to change the date format string to get this to convert).
Next, use
NSDateComponentsFormatter
to get your desired string:Today is July 28, so the result for that string is "About 2 weeks". The
allowedUnits
attribute is a bit field, so you can specify as many unit types as you want to allow.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 forstringFromTimeInterval(_:)
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 toTTTTimeIntervalFormatter
. 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: