iOS 開發(fā)中我們經常用到獲取系統(tǒng)時間,正常來說,我們只需要調用系統(tǒng)API即可
let currentDate = Date()
let formatter = DateFormatter()
// 系統(tǒng)設置時區(qū)
formatter.timeZone = TimeZone.current
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss,EEE"
print(formatter.string(from: currentDate))
但是這種獲取方式在用戶修改了時間或者修改了時區(qū)后,我們再獲取的話就會有誤差
如何解決呢,主要有兩種方式
- 服務器接口獲取
- 通過 URLSession 獲取
第一種方式我們就不多說了,主要介紹一下第二種方法,直接上代碼
let url = URL(string: "https://www.sina.com")
guard let url = url else { return }
let request = URLRequest(url: url)
let session = URLSession.shared
let task = session.dataTask(with: request) { (dataValue, response, error) in
// 容錯處理不做介紹了,直接獲取
let httpResponse: HTTPURLResponse = response as! HTTPURLResponse
// 打印獲取的數據,打印結果在下方
print(httpResponse.allHeaderFields)
let httpValue: [AnyHashable:Any] = httpResponse.allHeaderFields
let date = httpValue["Date"] as? String
if let dateValue = date {
// 時間格式
let formatter = DateFormatter()
formatter.timeZone = TimeZone.init(abbreviation: "GMT")
formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzzz"
// 為了簡單直接強解了
let formatterDate = formatter.date(from: dateValue)!
print("獲取到的時間\(formatterDate)")
// 自行處理時間,這里直接轉成東八區(qū)了
formatter.timeZone = TimeZone(abbreviation: "GMT+0800")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let cnTime = formatter.string(from: formatterDate)
print("轉換國內時間\(cnTime)")
}
}
task.resume()
返回 response 結果如下,清除了部分無用信息
{
"Cache-Control" = "max-age=120";
"Content-Encoding" = gzip;
"Content-Length" = 10360;
"Content-Type" = "text/html";
Date = "Thu, 03 Mar 2022 09:42:57 GMT";
}
通過方式二獲取到的時間及系統(tǒng)Date()獲取結果對比
修改系統(tǒng)時區(qū)及時間后,Date()獲?。?022-03-01 02:49:20,Tue
通過方式二獲取到的時間: 2022-03-03 09:49:59 +0000
通過方式二轉換國內時間: 2022-03-03 17:49:59