Swift 对时间的显示样式处理(朋友圈、微博发布时间)

显示时间需求.jpg

废话没有,直接看代码

  extension NSDate {
//对时间的处理
//传入的时间戳精确到毫秒
    public  class func created_at(date:Double)->String{
    
    let myDate = NSDate.init(timeIntervalSince1970: date / 1000 )
    
    let fmt  = DateFormatter()
    fmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
    fmt.locale = NSLocale(localeIdentifier: "en_US") as Locale?
    //获得当前时间
    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
 }

}
1B0221AF85DA4D4D89ABCFCD20ED7245.jpg
注意需要精确到毫秒的时间戳哦,复制这段代码去试试吧🙂🙂🙂🙂🙂🙂
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,966评论 25 709
  • 开发了将近一年的项目,不停的重复着做一些重复的事。其中有很多是在更新迭代以及再开发的过程中,不断得以改进的地方。对...
    gzejia阅读 251评论 0 1
  • 昨天,情人节加元宵节,特别的日子,听说19年轮回一次,下一次就肯定就老啦。昨天本来计划去 爬山踏青,孰知睡过头啦,...
    那个流沙阅读 201评论 0 1
  • 一、产品信息 1.产品名称:Instagram 2.版本号v40.0 3.体验环境 手机版本:iPhone x i...
    神经三只羊阅读 3,989评论 0 2
  • 17年11月10日,用手机打开收音机,信号总是不好,滋滋啦啦的声音一直不断,换了各个方向总也调不好,心里有点沮丧。...
    清水之味阅读 145评论 0 0