How to convert NSDate in to relative format as “Today”,“Yesterday”,“a week ago”,“a month ago”,“a year ago”?

前端 未结 16 2052
天命终不由人
天命终不由人 2020-11-28 22:08

I want to convert nsdate in to relative format like \"Today\",\"Yesterday\",\"a week ago\",\"a month ago\",\"a year ago\",\"date as it is\".

I have writ

16条回答
  •  失恋的感觉
    2020-11-28 22:41

    let formatter = DateComponentsFormatter()
    formatter.unitsStyle = .full
    
    let now = NSDate()
    
    
    let dateMakerFormatter = DateFormatter()
    
    dateMakerFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss z"
    let dateString = "2017-03-13 10:38:54 +0000"
    let stPatricksDay = dateMakerFormatter.date(from: dateString)!
    
    
    let calendar = NSCalendar.current
    
    
    
    let components = calendar.dateComponents([.hour, .minute,.weekOfMonth,.day,.year,.month,.second], from: stPatricksDay, to: now as Date)
    
    
    
    if components.year! > 0 {
        formatter.allowedUnits = .year
    } else if components.month! > 0 {
        formatter.allowedUnits = .month
    } else if components.weekOfMonth! > 0 {
        formatter.allowedUnits = .weekOfMonth
    } else if components.day! > 0 {
        formatter.allowedUnits = .day
    } else if components.hour! > 0 {
        formatter.allowedUnits = .hour
    } else if components.minute! > 0 {
        formatter.allowedUnits = .minute
    } else {
        formatter.allowedUnits = .second
    }
    
    let formatString = NSLocalizedString("%@ ago", comment: "Used to say how much time has passed. e.g. '2 hours ago'")
    
     let timeString = formatter.string(from: components)
    
    String(format: formatString, timeString!)
    

提交回复
热议问题