1.获取当前日期和周几
let today:Date = Date()
let myDateFormatter:DateFormatter = DateFormatter()
myDateFormatter.dateFormat = "yyyy-MM-dd"
var dateString:String = ""
dateString = myDateFormatter.string(from: today.addingTimeInterval(0))
let interval = NSDate().timeIntervalSince1970
let day = Int(interval/(24*60*60))
var weekDay:String = ""
weekDay = String ((day+4)%7 == 0 ? 7 : (day+4)%7)
switch weekDay {
case "7":
weekDay = "周日"
case "1":
weekDay = "周一"
case "2":
weekDay = "周二"
case "3":
weekDay = "周三"
case "4":
weekDay = "周四"
case "5":
weekDay = "周五"
default:
weekDay = "周六"
}
2.根据时间戳推出天数和月份,当前周等
//获取当前时间戳
let firstDate = Date().timeIntervalSince1970
print(firstDate)
//根据时间戳推出后5天
for i in 0 ..<5{
let day = timeStamp + Int(i * (60 * 60 * 24))
let da = Date(timeIntervalSince1970 : TimeInterval(day))
let compoent = Calendar.current.dateComponents(in: TimeZone.current, from: da)
print(compoent.day)
print(compoent.month)
}
3.根据日期字符转换时间,timeStr: 日期字符串,如2017/09/04 12:40:26
class func getTimeDescriptionByTimeStr(timeStr:String,split:String = "/") -> String {
//先转换时间戳
let formater = DateFormatter()
formater.dateFormat = "yyyy\(split)MM\(split)dd HH:mm:ss"
if let dd = formater.date(from: timeStr){
let timeInt = Int64(dd.timeIntervalSince1970)
return K12DateUtils.getTimeDescription(timeStamp:timeInt.description)
}
return timeStr
}
4.时间戳转换时间描述
- parameter timeStamp: 时间戳字符串
- returns: 描述字符串 : 如“刚刚”、“5分钟前”。。。
class func getTimeDescription(timeStamp:String?) -> String {
if timeStamp == nil || (timeStamp?.isEmpty)!{
return ""
}
//获取参数的时间戳
guard let _time = Int64(timeStamp!) else {
return ""
}
//获取当前时间戳
let _now_time = Int64(Date().timeIntervalSince1970)
//是否在现在之后,若是则返回空
if _now_time < _time {
return ""
}
//计算时间差, 按时间差返回字符串
var showTime = ""
//得到间隔,单位:秒
let _interval = _now_time - _time
if (_interval < 10) {
showTime = "刚刚"
} else if (_interval < 60) {
showTime = String(_interval) + "秒前"
} else if (_interval < 60 * 60) {
showTime = String(_interval / 60) + "分钟前"
} else if (_interval < 60 * 60 * 24) {
showTime = String(_interval / (60*60)) + "小时前"
}else if (_interval < 60 * 60 * 24 * 7) {
//7天以内,用 “几天前”显示
let tian = Int(_interval/(60 * 60 * 24))
showTime = String(tian) + "天前"
} else {
let _date = Date(timeIntervalSince1970: Double(_time))
let _dateFormatter = DateFormatter()
_dateFormatter.dateFormat = "yyyy-MM-dd"
showTime = _dateFormatter.string(from: _date as Date)
}
return showTime
}
5.时间戳转时间
//时间戳
let timeStamp =1463241600
//转换为时间
let timeInterval:NSTimeInterval =NSTimeInterval(timeStamp)
let date = NSDate(timeIntervalSince1970: timeInterval)
let dateformatter = NSDateFormatter()
dateformatter.dateFormat ="yyyy年MM月dd日 HH:mm:ss" //自定义日期格式
let time = dateformatter.stringFromDate(date)
print("对应时间:"+time)