Search code examples
swiftcocoa-touchdatetimensdateformatterswift2

Date/Time Natural Language Approximation in Swift


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.


Solution

  • You need two steps. First, convert your date string to an NSDate:

    let dateString = "2015-07-14T13:51:05.423Z"
    
    let df = NSDateFormatter()
    df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    let date = df.dateFromString(dateString)
    

    (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:

    let formatter = NSDateComponentsFormatter()
    formatter.unitsStyle = NSDateComponentsFormatterUnitsStyle.Full
    formatter.includesApproximationPhrase = true
    formatter.includesTimeRemainingPhrase = false
    formatter.allowedUnits = NSCalendarUnit.WeekOfMonthCalendarUnit
    
    if let pastDate = date {
        let dateRelativeString = formatter.stringFromDate(pastDate, toDate: NSDate())
    }
    

    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.