程序员

Swift 时间与时间戳转换,生成几分钟前几小时前

2017-11-16  本文已影响0人  大_瓶_子

根据时间戳转化为刚刚,几分钟前

//MARK: -根据后台时间戳返回几分钟前,几小时前,几天前
  func updateTimeToCurrennTime(timeStamp: Double) -> String {
        //获取当前的时间戳
        let currentTime = Date().timeIntervalSince1970
        print(currentTime,   timeStamp, "sdsss")
        //时间戳为毫秒级要 / 1000, 秒就不用除1000,参数带没带000
        let timeSta:TimeInterval = TimeInterval(timeStamp / 1000)
        //时间差
        let reduceTime : TimeInterval = currentTime - timeSta
        //时间差小于60秒
        if reduceTime < 60 {
            return "刚刚"
        }
        //时间差大于一分钟小于60分钟内
        let mins = Int(reduceTime / 60)
        if mins < 60 {
            return "\(mins)分钟前"
        }
        let hours = Int(reduceTime / 3600)
        if hours < 24 {
            return "\(hours)小时前"
        }
        let days = Int(reduceTime / 3600 / 24)
        if days < 30 {
            return "\(days)天前"
        }
        //不满足上述条件---或者是未来日期-----直接返回日期
        let date = NSDate(timeIntervalSince1970: timeSta)
        let dfmatter = DateFormatter()
        //yyyy-MM-dd HH:mm:ss
        dfmatter.dateFormat="yyyy年MM月dd日 HH:mm:ss"
        return dfmatter.string(from: date as Date)
    }

这里主要是一般后台返回的时间戳是毫秒级,要除1000
自己生成的是秒级不用除1000

    //MARK: -时间戳转时间函数
    class func timeStampToString(timeStamp: Double)->String {
        //时间戳为毫秒级要 / 1000, 秒就不用除1000,参数带没带000
        let timeSta:TimeInterval = TimeInterval(timeStamp / 1000)
        let date = NSDate(timeIntervalSince1970: timeSta)
        let dfmatter = DateFormatter()
        //yyyy-MM-dd HH:mm:ss
        dfmatter.dateFormat="yyyy年MM月dd日 HH:mm:ss"
        return dfmatter.string(from: date as Date)
    }

时间转时间戳要注意后台返回的日期格式,或者自己生成的日期格式, 年月日 可能是 2017/11/11

    //MARK: -时间转时间戳函数
    func timeToTimeStamp(time: String) -> Double {
        let dfmatter = DateFormatter()
        //yyyy-MM-dd HH:mm:ss
        dfmatter.dateFormat="yyyy年MM月dd日 HH:mm:ss"
        let last = dfmatter.date(from: time)
        let timeStamp = last?.timeIntervalSince1970
        return timeStamp!
    }
上一篇 下一篇

猜你喜欢

热点阅读