Kayamba Mukanzu Kayamba Mukanzu -5 years ago 231
Swift Question

NSDateFormatter. Setting time elapsed since date in swift

I'm looking to call a function that checks time elapsed since date. This will determine how the timeLable displays in my messages view controller, similar to IMessage.

The code I'm using below only shows HH:MM

let date = dateFormatter().dateFromString((recent["date"] as? String)!)

timeLabel.text = NSDateFormatter.localizedStringFromDate(date!, dateStyle: NSDateFormatterStyle.NoStyle, timeStyle: NSDateFormatterStyle.NoStyle)

I'm looking to change it to something along the lines of:

  • If date is today, date = "HH:MM"

  • If date is Yesterday, date = "Yesterday"

  • If date is the day before yesterday and so on, date = "Monday, Tuesday, Wednesday..."

  • If date is over 1 week, date = MM/DD/YY

Answer Source

Or try this. Note that we have to use components:fromDate: and then use components:fromDateComponents:toDateComponents:options: because if we don't 23:59 last night returns 23:59 instead of Yesterday.

extension NSDateFormatter {
    static func friendlyStringForDate(date:NSDate) -> String {
        // Fetch the default calendar
        let calendar = NSCalendar.currentCalendar()

        // Compute components from target date
        let from = calendar.components([.Day, .Month, .Year], fromDate: date)

        // Compute components from current date
        let to = calendar.components([.Day, .Month, .Year], fromDate: NSDate())

        // Compute days difference between the two
        let delta = calendar.components(.Day, fromDateComponents: from, toDateComponents: to, options: [])

        switch delta.day {
        case 0:
            let formatter = NSDateFormatter()
            formatter.timeZone = NSTimeZone.defaultTimeZone()
            formatter.dateFormat = "HH:mm"
            return formatter.stringFromDate(date)

        case 1:
            return "Yesterday"

        case 2..<7:
            let formatter = NSDateFormatter()
            formatter.timeStyle = .NoStyle
            formatter.dateFormat = "EEEE"
            return formatter.stringFromDate(date)

            let formatter = NSDateFormatter()
            formatter.timeStyle = .NoStyle
             formatter.dateFormat = "MM/dd/YY"
            return formatter.stringFromDate(date)

Now then, to use it just:

timeLabel.text = NSDateFormatter.friendlyStringForDate(date!)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download