//獲取當前系統(tǒng)的時間
static func getCurrentSystemDate() -> Date{
let date = Date() // 獲得時間對象
let zone = NSTimeZone.system // 獲得系統(tǒng)的時區(qū)
let time = zone.secondsFromGMT(for: date)// 以秒為單位返回當前時間與系統(tǒng)格林尼治時間的差
return date.addingTimeInterval(TimeInterval(time))// 然后把差的時間加上,就是當前系統(tǒng)準確的時間
}
//根據(jù)字符串獲取當前時區(qū)的時間
static func date(_ date: String?, dateFormat: String = "yyyy-MM-dd") -> Date? {
guard let date = date else {
return nil
}
let dateformatter = DateFormatter()
dateformatter.timeZone = TimeZone.init(secondsFromGMT: 0)
dateformatter.dateFormat = dateFormat
return dateformatter.date(from: date)
}
調(diào)用:
print(Date.getCurrectSystemDate())
print(Date.date("2021-12-12"))
The Result:

image.png