美文网首页
时间戳与时间互相转换 聊天消息通用

时间戳与时间互相转换 聊天消息通用

作者: 小伟Five | 来源:发表于2018-01-14 11:57 被阅读25次
    # Swift
    
    func timestampChangeToTimeString(_ timestamp: TimeInterval) -> String {
        let dateFormatter: DateFormatter = DateFormatter()
        let dateBefore = Date(timeIntervalSince1970: timestamp)
        let before = NSCalendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second, .weekOfYear, .weekday, .weekdayOrdinal], from: dateBefore)
        let now = NSCalendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second, .weekOfYear, .weekday, .weekdayOrdinal], from: Date())
        
        if before.year == now.year  {
            if before.month == now.month {
                if before.day == now.day {
                    if before.minute! < 5{
                        return "刚刚"
                    }else if before.hour! < 1{
                        return "\(String(describing: before.minute))分钟之前"
                    }else if before.hour! < 5 && before.hour! >= 1{
                        return "\(String(describing: before.hour))小时之前"
                    }else{
                        dateFormatter.dateFormat = "HH:mm"
                    }
                } else if before.day! + 1 == now.day {
                    dateFormatter.dateFormat = "昨天 HH:mm"
                } else if before.day! + 2 == now.day {
                    dateFormatter.dateFormat = "前天 HH:mm"
                } else {
                    dateFormatter.dateFormat = "MM-dd HH:mm"
                }
            } else {
                dateFormatter.dateFormat = "MM-dd HH:mm"
            }
        } else {
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
        }
        return dateFormatter.string(from: dateBefore)
    }
    

    # 简单使用  
    
            //时间戳
            let timeStamp = 1515666666
            let timeInterval:TimeInterval = TimeInterval(timeStamp)
            print("时间戳转化为对应的时间=====\(timestampChangeToTimeString(timeInterval))")
    
    
     # 当然我们网络数据解析多为String 方法略做更改就可使用
     # 更改后的方法 
       func timestampChangeToTimeStringsss(_ timeStr: String) -> String {
            let dateFormatter: DateFormatter = DateFormatter()
            let timeInterval:TimeInterval = TimeInterval(timeStr)!
            let dateBefore = Date(timeIntervalSince1970:timeInterval)
            ........
         }
    
    # 更改后的使用
            print("时间戳转化为对应的时间========\(timestampChangeToTimeStringsss("1515666666"))")
    
    

    相关文章

      网友评论

          本文标题:时间戳与时间互相转换 聊天消息通用

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