Tools

swift时间的一个处理

2019-06-20  本文已影响0人  凡尘一笑

代码实现

      
          let  fmt = DateFormatter()
        fmt.dateFormat = "EEE MM dd HH:mm:ss Z yyyy"
        fmt.locale = NSLocale(localeIdentifier: "en") as Locale
    
        // 2.将字符串时间,转成NSDate类型
        guard let ceateDate = fmt.date(from: createAtstr) else {
            return ""
        }
        
        let nowDate = NSDate()
        let interval = nowDate.timeIntervalSince(ceateDate)

        if interval < 60 {
            return "刚刚"
        }
    
        if interval < (60 * 60) {
        return "\(Int(interval) / 60)分钟前"
        }
    
        if interval < (60 * 60 * 24){
        return "\(Int(interval)/(60 * 60))小时前"
        }
    
        let calendar = NSCalendar.current
        if calendar.isDateInYesterday(ceateDate){
        fmt.dateFormat = "昨天 HH:mm"
        return fmt.string(from: ceateDate)
        }
    
        let gap = calendar.dateComponents([Calendar.Component.year], from: ceateDate, to: nowDate as Date)
    
        if gap.year! < 1 {
        fmt.dateFormat = "MM-dd HH:mm"
        return fmt.string(from: ceateDate)
        }
    
        fmt.dateFormat = "yyyy-MM-dd HH:mm"
        return fmt.string(from: ceateDate)

第一步

image.png

第二步

image.png

第三步

代码呈上
https://gitee.com/lanyingwei/codes/bo9tp4g0hkeq6m31fzsdi33

上一篇 下一篇

猜你喜欢

热点阅读