使用這樣的函式獲取用戶當前位置的當前日期、小時、分鐘等是相當簡單的,只要您有 UTC 資料:
func getHourForDate(_ date: Date?)-> String{
guard let date = date else {return "error"}
//initialize formatter
let formatter = DateFormatter()
//set format to 12 hour clock with am/pm
formatter.dateFormat = "h a"
//return formatting string
return formatter.string(from: date)
}
我遇到的問題是,當我嘗試決議來自世界各地的資料時,該功能只會根據我自己的位置給我時間。OpenWeather 似乎提供了一些資料來解決這個問題。看看我創建的天氣回應中的幾個引數:
struct WeatherResponse: Codable {
let timezone: String
let timezone_offset: Int
}
所以我有一個字串,它給了我像“大西洋”這樣的資料,以及一個像“-14400”這樣的偏移量。問題是我不知道如何應用這些資料。簡單地從 API 提供的 UTC 時間中減去 timezone_offset 似乎是不正確的。我嘗試了類似下面提供的代碼,但它似乎只在我使用我的實際當前位置在手機上運行應用程式時才有效,而不是當我嘗試將世界各地的其他位置模擬為我的當前位置時:
//get the difference of my current location timezone offset and the offset of each json response
//(this should cancel out any offset for my current location)
let timezoneDifference = currentLocationTimezoneOffset - timezone_offset
//subtract the offset from the hour date provided by the json
let offset = utcFromJson - timezoneDifference
//pass the offset into the function to return a formatted date string
let hourLabel.text = getHourForDate(Date(timeIntervalSince1970: TimeInterval(offset)
我希望這個問題是直截了當的,或者我沒有遺漏任何有用的資訊。任何幫助表示贊賞,謝謝!
uj5u.com熱心網友回復:
您可以嘗試一些簡單的方法,例如此示例代碼,以獲取“其他”位置的時間:
let timeHere = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "LLLL dd, hh:mm:ss a"
dateFormatter.timeZone = TimeZone(secondsFromGMT: response.timezone_offset) // <-- here
let timeThere = dateFormatter.string(from: timeHere)
print("timeHere: \(timeHere) timeThere: \(timeThere) \n")
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/451000.html
標籤:json 迅速 日期 时区 nsdateformatter
下一篇:已發布的布爾變數自動重置
