1.保存系统当前时间
//MARK: - 获取当前时间转为字符串
class func saveCurrentTime() {
let nowDate = NSDate()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateString = formatter.string(from: nowDate as Date)
UserDefaults.standard.set(dateString, forKey: "currentDate")
UserDefaults.standard.synchronize()
}
2.计算时间差(先转为时间戳在进行计算)
func fun_Interval() {
//时间格式化
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
//设置第一个时间戳
let firstDateString = "2017-02-27 11:11:11"
let firstDate = formatter.date(from: firstDateString)
let firstInterval :TimeInterval = (firstDate?.timeIntervalSince1970)!
//设置第二个时间戳
let secondDateString = "2017-02-27 11:11:21"
let secondDate = formatter.date(from: secondDateString)
let secondInterval: TimeInterval = (secondDate?.timeIntervalSince1970)!
let interval = secondInterval - firstInterval
print("interval = \(interval)") //输出结果为10.0,计算的结果单位是S
}