时间戳与时间互相转换 聊天消息通用
2018-01-14 本文已影响25人
小伟Five
# 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"))")