Swift display time ago from Date (NSDate)

Viewed 17373

In a cell I want to display the time ago from the NSDate in the Parse server. Here is the code but its not working. Nothing is changing, and the data isn't being parsed.

    if let createdat = (object?["createdAt"] as? String){
            let pastDate = Date(timeIntervalSinceNow: TimeInterval(createdat)!)
            cell.TimeAgo.text = pastDate.timeAgoDisplay()
        }


       extension Date {
          func timeAgoDisplay() -> String {
        let secondsAgo = Int(Date().timeIntervalSince(self))

        let minute = 60
        let hour = 60 * minute
        let day = 24 * hour
        let week = 7 * day

        if secondsAgo < minute {
            return "\(secondsAgo) sec ago"
        } else if secondsAgo < hour {
            return "\(secondsAgo / minute) min ago"
        } else if secondsAgo < day {
            return "\(secondsAgo / hour) hrs ago"
        } else if secondsAgo < week {
            return "\(secondsAgo / day) days ago"
        }

        return "\(secondsAgo / week) weeks ago"
    }
}
8 Answers

Swift 5.1 (iOS 13)

Since iOS 13 you can use Apple's RelativeDateFormatter. The advantage is the resulting string is localized.

let date = Date().addingTimeInterval(-15000)

let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = .full
let string = formatter.localizedString(for: date, relativeTo: Date())

print(string) // 4 hours ago

See for example this blog post.

Here is the solution in Swift 5:

extension Date {

func timeAgo() -> String {

    let secondsAgo = Int(Date().timeIntervalSince(self))

    let minute = 60
    let hour = 60 * minute
    let day = 24 * hour
    let week = 7 * day
    let month = 4 * week

    let quotient: Int
    let unit: String
    if secondsAgo < minute {
        quotient = secondsAgo
        unit = "second"
    } else if secondsAgo < hour {
        quotient = secondsAgo / minute
        unit = "min"
    } else if secondsAgo < day {
        quotient = secondsAgo / hour
        unit = "hour"
    } else if secondsAgo < week {
        quotient = secondsAgo / day
        unit = "day"
    } else if secondsAgo < month {
        quotient = secondsAgo / week
        unit = "week"
    } else {
        quotient = secondsAgo / month
        unit = "month"
    }
    return "\(quotient) \(unit)\(quotient == 1 ? "" : "s") ago"
}
}

It's a bit tricky)

Basically u need to

  • check interval
  • select interested components
  • check if quotient required and if it's applicable for the current language

iOS provide few ways to do this

  1. DateComponentsFormatter

    +: no work with localization and other string-related stuff

    -: not very flexible

    let formatter = DateComponentsFormatter()
    formatter.allowedUnits = [.hour, .minute, .second]
    formatter.unitsStyle = .brief
    formatter.zeroFormattingBehavior = .dropAll
    
    let result = formatter.string(from: Date().advanced(by: -300), to: Date())
    result
    

Result:

"5min"

  1. RelativeDateTimeFormatter

    +: no work with localization and other string-related stuff

    -: iOS13+

    let formatter = RelativeDateTimeFormatter()
    formatter.unitsStyle = .full
    return formatter.localizedString(for: self, relativeTo: Date())
    
  2. Custom way

    +: flexible

    -: code everything

Sample:

import Foundation

public extension Date {

  struct DetailedDateSuffix {

    let year: String
    let month: String
    let week: String
    let day: String
    let hour: String
    let min: String
    let second: String

    let quotient: String
    let suffix: String

    public init(year: String,
                week: String,
                month: String,
                day: String,
                hour: String,
                min: String,
                second: String,
                quotient: String,
                suffix: String = String.empty) {
      self.year = year
      self.month = month
      self.week = week
      self.day = day
      self.hour = hour
      self.min = min
      self.second = second
      self.quotient = quotient
      self.suffix = suffix
    }
  }

  func toDetailedReadableFormat(_ suffix: DetailedDateSuffix) -> String {

    if #available(iOS 13.0, *) {
      let formatter = RelativeDateTimeFormatter()
      formatter.unitsStyle = .full
      return formatter.localizedString(for: self, relativeTo: Date())
    } else {
      let calendar = Calendar.current
      let ageComponents = calendar.dateComponents(
        [
          .year,
          .month,
          .weekOfYear,
          .day,
          .hour,
          .minute,
          .second
        ],
        from: self,
        to: Date())

      var description: String = String.empty

      if let years = ageComponents.year,
        let months = ageComponents.month,
        let weeks = ageComponents.weekOfYear,
        let days = ageComponents.day,
        let hours = ageComponents.hour,
        let min = ageComponents.minute,
        let sec = ageComponents.second {

        var requireQuotient = false

        if years > 0 {
          description = "\(years)" + suffix.year
          requireQuotient = years == 1
        } else if months > 0 {
          description = "\(months)" + suffix.month
          requireQuotient = months == 1
        } else if weeks > 0 {
          description = "\(weeks)" + suffix.week
          requireQuotient = weeks == 1
        } else if days > 0 {
          description = "\(days)" + suffix.day
          requireQuotient = days == 1
        } else if hours > 0 {
          description = "\(hours)" + suffix.hour
          requireQuotient = hours == 1
        } else if min > 0 {
          description = "\(min)" + suffix.min
          requireQuotient = min == 1
        } else if sec > 0 {
          description = "\(sec)" + suffix.second
          requireQuotient = sec == 1
        }

        description = requireQuotient ? "\(description)\(suffix.quotient)" : description
        description = "\(description)\(suffix.suffix)"
      }

      return description
    }
  }
}

Pass time as String in format e.g. 2019-02-25 10:20:21 Pass dateformat in Variable dateFormat

let dateFormat = "yyyy-MM-dd HH:mm:ss"

    func timeInterval(timeAgo:String) -> String
        {
            let df = DateFormatter()

            df.dateFormat = dateFormat
            let dateWithTime = df.date(from: timeAgo)

            let interval = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: dateWithTime!, to: Date())

            if let year = interval.year, year > 0 {
                return year == 1 ? "\(year)" + " " + "year ago" : "\(year)" + " " + "years ago"
            } else if let month = interval.month, month > 0 {
                return month == 1 ? "\(month)" + " " + "month ago" : "\(month)" + " " + "months ago"
            } else if let day = interval.day, day > 0 {
                return day == 1 ? "\(day)" + " " + "day ago" : "\(day)" + " " + "days ago"
            }else if let hour = interval.hour, hour > 0 {
                return hour == 1 ? "\(hour)" + " " + "hour ago" : "\(hour)" + " " + "hours ago"
            }else if let minute = interval.minute, minute > 0 {
                return minute == 1 ? "\(minute)" + " " + "minute ago" : "\(minute)" + " " + "minutes ago"
            }else if let second = interval.second, second > 0 {
                return second == 1 ? "\(second)" + " " + "second ago" : "\(second)" + " " + "seconds ago"
            } else {
                return "a moment ago"

            }
        }
    let now = Date()
let pastDate = Date(timeIntervalSinceNow: -60 * 60 * 24)

enum DisplayTime {
    case short
    case long

    var seconds: String {
        switch self {
        case .short: return "s"
        case .long: return "seconds"
        }
    }

    var minutes: String {
        switch self {
        case .short: return "m"
        case .long: return "minutes"
        }
    }

    var hours: String {
        switch self {
        case .short: return "h"
        case .long: return "hours"
        }
    }

    var days: String {
        switch self {
        case .short: return "d"
        case .long: return "days"
        }
    }

    var weeks: String {
        switch self {
        case .short: return "w"
        case .long: return "weeks"
        }
    }
}

extension Date {

    func timeAgoDisplay(_ display: DisplayTime) -> String {

        let secondsAgo = Int(Date().timeIntervalSince(self))

        let minute = 60
        let hour = 60 * minute
        let day = 24 * hour
        let week = 7 * day

        switch secondsAgo {
        case let seconds where seconds < minute : return "\(secondsAgo) \(display.seconds) ago"
        case let seconds where seconds < hour: return "\(secondsAgo / minute) \(display.minutes) ago"
        case let seconds where seconds < day: return "\(secondsAgo / hour) \(display.hours) ago"
        case let seconds where seconds < week: return "\(secondsAgo / day) \(display.days) ago"
        default: "\(secondsAgo / week) \(display.weeks) ago"
        }
        return "\(secondsAgo / week) \(display.weeks) ago"
    }
}

pastDate.timeAgoDisplay(.short)

Finally got a simple solution for me in swift4.2

    let start = //Enter Start Date here....
    let end = Date()
    let formatter = DateComponentsFormatter()
    formatter.maximumUnitCount = 2
    formatter.unitsStyle = .full
    formatter.allowedUnits = [.year, .month, .day]
    let timeDifference = form.string(from: start, to: end)
    print(timeDifference)
    if timeDifference == "0 days"{
          print("Today")
    }
    else if  timeDifference == "1 days"{
           print("\(timeDifference!)day ago")
    }
    else{
           print("\(timeDifference!)days ago")
    }

If you have only timestamp from 1970. You can use this function to return time ago.

private func timestampToStringAgo(timestamp: Int64) -> String{
        let actualTime = Int64(Date().timeIntervalSince1970*1000)
        var lastSeenTime = actualTime - timestamp
        lastSeenTime /= 1000 //seconds
        var lastTimeString = ""
        if lastSeenTime < 60 {
            if lastSeenTime == 1 {
                lastTimeString = String(lastSeenTime) + " second ago"
            } else {
                lastTimeString = String(lastSeenTime) + " seconds ago"
            }
        } else {
            lastSeenTime /= 60
            if lastSeenTime < 60 {
                if lastSeenTime == 1 {
                    lastTimeString =  String(lastSeenTime) + " minute ago"
                } else {
                    lastTimeString =  String(lastSeenTime) + " minutes ago"
                }
                
            } else {
                lastSeenTime /= 60
                if lastSeenTime < 24 {
                    if lastSeenTime == 1 {
                        lastTimeString = String(lastSeenTime) + " hour ago"
                    } else {
                        lastTimeString = String(lastSeenTime) + " hours ago"
                    }
                } else {
                    lastSeenTime /= 24
                    if lastSeenTime == 1 {
                        lastTimeString = String(lastSeenTime) + " day ago"
                    } else {
                        lastTimeString = String(lastSeenTime) + " days ago"
                    }
                }
            }
        }
        return lastTimeString
    }
Related