前言
因项目需要 界面需要展示时间信息,具体逻辑如下:
根据后台返回时间戳来判断时间是否为今天或昨天,如果不是再判断是否是本周(每周的第一天为周日),如果还不是直接转成年月日。。。
废话不多说,直接上代码:
//日期显示--今天--周几
class func detailDate24Week(time:Double) -> String{
let formatter = DateFormatter()
formatter.dateStyle = DateFormatter.Style.medium
formatter.timeStyle = DateFormatter.Style.short
formatter.dateFormat = "YYYY-MM-dd HH:mm:ss"
let timeInterval = TimeInterval(time/1000.0)
//获取到date
let confromTimesp = Date.init(timeIntervalSince1970: timeInterval)
var calender = NSCalendar.current
// 设置区域
calender.locale = Locale.init(identifier: "zh_CN")
// 设置时区
/*
设置时区,设置为 GMT+8,即北京时间(+8)
*/
calender.timeZone = TimeZone.init(abbreviation: "EST")!
calender.timeZone = TimeZone.init(secondsFromGMT: +28800)!
// 设定每周的第一天从星期几开始
/*
1 代表星期日开始,2 代表星期一开始,以此类推。默认值是 1
*/
calender.firstWeekday = 1
//ordinalityOfUnit
let timeWeek = calender.component(.weekOfYear, from: confromTimesp)
let systimeWeek = calender.component(.weekOfYear, from: Date.init())
if calender.isDateInToday(confromTimesp) {
return "今天"
}else if calender.isDateInYesterday(confromTimesp) {
return "昨天"
}else if timeWeek == systimeWeek {
let weeks = ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"]
let i = calender.ordinality(of: .weekday, in: .weekOfYear, for: confromTimesp)
//此处一定要记得减1
return weeks[i!-1]
}else{
return SwiftFactory.getCurrentTime(timeNum: time, format: "MM-dd")
}
}
//MARK: - 时间格式转换"YYYY-MM-dd HH:mm:ss"
class func getCurrentTime(timeNum:Double , format:String) -> String {
let formatter = DateFormatter()
formatter.dateStyle = DateFormatter.Style.medium
formatter.timeStyle = DateFormatter.Style.short
formatter.dateFormat = format
let timeInterval = TimeInterval(timeNum/1000.0)
let confromTimesp = NSDate(timeIntervalSince1970:timeInterval)
let confromTimespStr = formatter.string(from: confromTimesp as Date)
return confromTimespStr
}
新手第一次发帖如有不足请指出。。。