消息的时间戳处理 一分钟前?

    func created_at(dateStr:String)->String{
        let fmt  = DateFormatter()
        fmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
        //fmt.locale = NSLocale(localeIdentifier: "en_US") as Locale?
        let myDate = fmt.date(from: dateStr) ?? Date()
        //获得当前时间
        let now = NSDate()
        //计算时间差
        let interval = now.timeIntervalSince(myDate as Date)
        // 处理小于一分钟的时间
        if interval < 60 {
            return "刚刚"
        }
        // 处理小于一小时的时间
        if interval < 60 * 60 {
            return "\(interval / 60)分钟前"
        }
        // 处理小于一天的时间
        if interval < 60 * 60 * 24 {
            return "\(interval / (60 * 60))小时前"
        }
        // 处理昨天时间
        let calendar = Calendar.current
        if calendar.isDateInYesterday(myDate as Date) {
            fmt.dateFormat = "昨天 HH:mm"
            let timeStr  = fmt.string(from: myDate as Date)
            return timeStr
        }
        //处理一年之内的时间
        let cmp  = calendar.dateComponents([.year,.month,.day], from: myDate as Date, to: now as Date)
        if cmp.year! < 1 {
            fmt.dateFormat = "MM-dd HH:mm"
            let timeStr  = fmt.string(from: myDate as Date)
            return timeStr
        }
        //超过一年的时间
        fmt.dateFormat = "yyyy-MM-dd HH:mm"
        let timeStr = fmt.string(from: myDate as Date)
        return timeStr
    }

传入的参数是 "yyyy-MM-dd HH:mm:ss" 样式的字符串
链接 https://www.jianshu.com/p/0516acb65fcf

你可能感兴趣的:(消息的时间戳处理 一分钟前?)