Swift display time ago from Date (NSDate)

╄→尐↘猪︶ㄣ 提交于 2019-11-28 03:24:31

问题


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"
    }
}

回答1:


If you just want a Time Ago extension for Date go to the bottom of the answer 😊

I'll show you an example just to get seconds ago and after I'll show your extension updated.

Note: you can use directly the date from Pase if you want:

if let pastDate = (object?["createdAt"] as? Date){
        cell.TimeAgo.text = pastDate.timeAgoDisplay()
    }

Example how to get seconds ago with Swift 3 or Swift 4:

First: To get the number of seconds ago we need to check if we have one minutes or less, to get the current Date minus one minute you can write that:

let minuteAgo = calendar.date(byAdding: .minute, value: -1, to: Date())!

Second: Now compare the 2 dates! (In the case of your extension we replace yourDate by self) and get the difference between this 2 dates.

if (minuteAgo < yourDate) {
    let diff = Calendar.current.dateComponents([.second], from: yourDate, to: Date()).second ?? 0
    print("\(diff) sec ago")
}

That's all, now you can print the time ago !

So your extension is like this: (This is a simple extension to get the time ago)

extension Date {
    func timeAgoDisplay() -> String {

        let calendar = Calendar.current
        let minuteAgo = calendar.date(byAdding: .minute, value: -1, to: Date())!
        let hourAgo = calendar.date(byAdding: .hour, value: -1, to: Date())!
        let dayAgo = calendar.date(byAdding: .day, value: -1, to: Date())!
        let weekAgo = calendar.date(byAdding: .day, value: -7, to: Date())!

        if minuteAgo < self {
            let diff = Calendar.current.dateComponents([.second], from: self, to: Date()).second ?? 0
            return "\(diff) sec ago"
        } else if hourAgo < self {
            let diff = Calendar.current.dateComponents([.minute], from: self, to: Date()).minute ?? 0
            return "\(diff) min ago"
        } else if dayAgo < self {
            let diff = Calendar.current.dateComponents([.hour], from: self, to: Date()).hour ?? 0
            return "\(diff) hrs ago"
        } else if weekAgo < self {
            let diff = Calendar.current.dateComponents([.day], from: self, to: Date()).day ?? 0
            return "\(diff) days ago"
        }
        let diff = Calendar.current.dateComponents([.weekOfYear], from: self, to: Date()).weekOfYear ?? 0
        return "\(diff) weeks ago"
    }
}

To use it, this is very straightforward:

var now = Date()
now.timeAgoDisplay()



回答2:


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"

            }
        }



回答3:


    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)



回答4:


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")
    }


来源:https://stackoverflow.com/questions/44086555/swift-display-time-ago-from-date-nsdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!