1.時間戳分類
extension TimeInterval {
? ? // 把秒數(shù)轉(zhuǎn)換成時間的字符串
? ? funcconvertString() ->String{
? ? ? ? // 把獲取到的秒數(shù)轉(zhuǎn)換成具體的時間
? ? ? ? letcreateDate =Date(timeIntervalSince1970:self)
? ? ? ? // 獲取當(dāng)前日歷
? ? ? ? letcalender =Calendar.current
? ? ? ? // 獲取日期的年份
? ? ? ? letcomps = calender.dateComponents([.year, .month, .day, .hour, .minute, .second], from: createDate, to:Date())
? ? ? ? // 日期格式
? ? ? ? letformatter =DateFormatter()
? ? ? ? // 判斷當(dāng)前日期是否為今年
? ? ? ? guardcreateDate.isThisYear()else{
? ? ? ? ? ? formatter.dateFormat="yyyy-MM-dd HH:mm:ss"
? ? ? ? ? ? returnformatter.string(from: createDate)
? ? ? ? }
? ? ? ? // 是否是前天
? ? ? ? ifcreateDate.isBeforeYesterday() {
? ? ? ? ? ? formatter.dateFormat="前天 HH:mm"
? ? ? ? ? ? returnformatter.string(from: createDate)
? ? ? ? }elseifcreateDate.isToday()||createDate.isYesterday() {
? ? ? ? ? ? // 判斷是否是今天或者昨天
? ? ? ? ? ? ifcomps.hour!>=1{
? ? ? ? ? ? ? ? returnString(format:"%d小時前", comps.hour!)
? ? ? ? ? ? }elseifcomps.minute!>=1{
? ? ? ? ? ? ? ? returnString(format:"%d分鐘前", comps.minute!)
? ? ? ? ? ? }else{
? ? ? ? ? ? ? ? return"剛剛"
? ? ? ? ? ? }
? ? ? ? }else{
? ? ? ? ? ? formatter.dateFormat="MM-dd HH:mm"
? ? ? ? ? ? returnformatter.string(from: createDate)
? ? ? ? }
? ? }
}
2.Date的分類
extension Date {
? ? /// 判斷當(dāng)前日期是否為今年
? ? funcisThisYear() ->Bool{
? ? ? ? // 獲取當(dāng)前日歷
? ? ? ? letcalender =Calendar.current
? ? ? ? // 獲取日期的年份
? ? ? ? letyearComps = calender.component(.year, from:self)
? ? ? ? // 獲取現(xiàn)在的年份
? ? ? ? letnowComps = calender.component(.year, from:Date())
? ? ? ? returnyearComps==nowComps
? ? }
? ? ///是否是昨天
? ? funcisYesterday() ->Bool{
? ? ? ? // 獲取當(dāng)前日歷
? ? ? ? letcalender =Calendar.current
? ? ? ? // 獲取日期的年份
? ? ? ? letcomps = calender.dateComponents([.year, .month, .day], from:self, to:Date())
? ? ? ? // 根據(jù)頭條顯示時間 咏雌,我覺得可能有問題 如果comps.day == 0 顯示相同饲梭,如果是 comps.day == 1 顯示時間不同
? ? ? ? // 但是 comps.day == 1 才是昨天 comps.day == 2 是前天
//? ? ? ? return comps.year == 0 && comps.month == 0 && comps.day == 1
? ? ? ? returncomps.year==0&&comps.month==0&&comps.day==0
? ? }
? ? ///是否是前天
? ? func isBeforeYesterday() -> Bool {
? ? ? ? // 獲取當(dāng)前日歷
? ? ? ? letcalender =Calendar.current
? ? ? ? // 獲取日期的年份
? ? ? ? letcomps = calender.dateComponents([.year, .month, .day], from:self, to:Date())
? ? ? ? //
//? ? ? ? return comps.year == 0 && comps.month == 0 && comps.day == 2
? ? ? ? returncomps.year==0&&comps.month==0&&comps.day==1
? ? }
? ? /// 判斷是否是今天
? ? funcisToday() ->Bool{
? ? ? ? // 日期格式化
? ? ? ? letformatter =DateFormatter()
? ? ? ? // 設(shè)置日期格式
? ? ? ? formatter.dateFormat="yyyy-MM-dd"
? ? ? ? letdateStr = formatter.string(from:self)
? ? ? ? letnowStr = formatter.string(from:Date())
? ? ? ? returndateStr==nowStr
? ? }
}