使用场景,聊天室,P2P聊天
struct TimeManager {
static func showTime(msglastTime : TimeInterval ,showDetail : Bool = false) -> String {
//今天的时间
let nowDate = Date()
let msgDate = Date(timeIntervalSince1970: msglastTime)
var result = ""
let components = Set<Calendar.Component>([.year, .month, .day ,.weekday ,.hour, .minute, ])
let nowDateComponents = Calendar.current.dateComponents(components, from: nowDate)
let msgDateComponents = Calendar.current.dateComponents(components, from: msgDate)
var hour = msgDateComponents.hour
let OnedayTimeIntervalValue = 24*60*60 //一天的秒数
result = TimeManager.getPeriodOfTime(time: hour!, minute: (msgDateComponents.minute)!)
if (hour! > 12)
{
hour = hour! - 12
}
if(nowDateComponents.day == msgDateComponents.day) //同一天,显示时间
{
result = String(format:"%@ %zd:%02d",result,(hour)!,(msgDateComponents.minute)!)
}
else if(nowDateComponents.day == ((msgDateComponents.day)!+1))//昨天
{
result = showDetail ? String(format:"昨天%@ %zd:%02d",result,(hour)!,(msgDateComponents.minute)!) : "昨天"
}
else if(nowDateComponents.day == ((msgDateComponents.day)! + 2)) //前天
{
result = showDetail ? String(format:"前天%@ %zd:%02d",result,(hour)!,(msgDateComponents.minute)!) : "前天";
}
else if(Int(nowDate.timeIntervalSince(msgDate)) < 7 * OnedayTimeIntervalValue)//一周内
{
let weekDay = TimeManager.weekdayStr(dayOfWeek: (msgDateComponents.weekday)!)
result = showDetail ? weekDay.appendingFormat("%@ %zd:%02d", result,hour!,(msgDateComponents.minute)!) : weekDay
}
else//显示日期
{
let day = String(format:"%zd-%zd-%zd", (msgDateComponents.year)!, (msgDateComponents.month)!, (msgDateComponents.day)!)
result = showDetail ? day.appendingFormat("%@ %zd:%02d",result,hour!,(msgDateComponents.minute)!) : day
}
return result;
}
static func getPeriodOfTime(time : Int ,minute : Int) -> String{
let totalMin = time * 60 + minute
var showPeriodOfTime = ""
if (totalMin > 0 && totalMin <= 5 * 60)
{
showPeriodOfTime = "凌晨"
}
else if (totalMin > 5 * 60 && totalMin < 12 * 60)
{
showPeriodOfTime = "上午"
}
else if (totalMin >= 12 * 60 && totalMin <= 18 * 60)
{
showPeriodOfTime = "下午"
}
else if ((totalMin > 18 * 60 && totalMin <= (23 * 60 + 59)) || totalMin == 0)
{
showPeriodOfTime = "晚上"
}
return showPeriodOfTime;
}
static func weekdayStr(dayOfWeek : Int) ->String{
var daysOfWeekDict : [Int : String] = [:]
daysOfWeekDict = [1 : "星期日" ,2 : "星期一" ,3 : "星期二" ,4 : "星期三" ,5 : "星期四" ,6 : "星期五" ,7 : "星期六"]
return (daysOfWeekDict[dayOfWeek])!
}
}