简体   繁体   中英

How to format a date like “5 min”, “1 hour,”, “Yesterday”, “1 Week ago”?

I am trying to get something similar to facebook post date/time. Like 1 min, 1 hour, Yesterday, Week ago etc.

This is the is function I am using to get this format: ( Oct-22 17:28 PM )

func convertTime(serverTime: Double)  -> String {
    let serverTime = serverTime
    let date = Date(timeIntervalSince1970: serverTime)
    let dateFomatter = DateFormatter()
    dateFomatter.dateFormat = "MMM-dd HH:mm a"
    let strDate = dateFomatter.string(from: date)
    print("This is the post's date: \(strDate)")

    return strDate
}

try this code

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.locale = Locale.init(identifier: "en_GB")
let before = dateFormatter.date(from: "2017-10-23 10:28:17")!

//getting the current time
let now = Date()

let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.zeroFormattingBehavior = .dropAll
formatter.maximumUnitCount = 1 
formatter.allowedUnits = [.year, .month, .weekOfMonth, .day, .hour, .minute]
formatter.includesApproximationPhrase = true 


let formatString = NSLocalizedString("%@ ago", comment: "e.g. '2 hours ago'")

let timeString = formatter.string(from: before, to: now)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM