美文网首页Tools
swift时间的一个处理

swift时间的一个处理

作者: 凡尘一笑 | 来源:发表于2019-06-20 20:37 被阅读0次
    • 如果时间比现在小于60秒,则显示刚刚

    • 如果时间比现在小于60分钟,则显示多少分钟前

    • 如果时间比现在小于24小时,则显示多少个小时前

    • 如果时间比现在超过24小时小于48小时,则显示昨天几点几分

    • 如果时间比现在间隔小于1年,则显示哪月哪天,几时几分

    • 其他的就显示哪年哪月哪天几时几分

    代码实现

          
              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

    第三步

    • 并提供一个类方法
    • 把刚才的代码放到类方法里面 外面直接调用即可


      image.png
      image.png
    • 使用


      image.png

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

    相关文章

      网友评论

        本文标题:swift时间的一个处理

        本文链接:https://www.haomeiwen.com/subject/yjnrqctx.html