當我在下面運行代碼時,回傳的日期和時間格式正確,但不是來自 API 的內容,在這種情況下,它currentVehicle.LastCommunicationDate!
不是來自 API 的時間,currentVehicle.LastCommunicationDate!而是回傳一個隨機時區,我認為這是來自服務器或類似的東西。
我現在擁有的代碼的輸出是:2022-01-21 02:04:15什么時候應該是我當地時區的實時時間,但它正在獲得不同的時區。
LastCommunicationDate來自郵遞員的資訊是 json 格式:"LastCommunicationDate": "2022-01-21T10:58:21.367",
我想要的時間是 Postman 剛剛從 json 轉換為正常時間的時間,例如: yyyy-MM-dd HH:mm:ss
let timeinterval : TimeInterval = (currentVechicle.LastCommunicationDate! as NSString).doubleValue
let dateFromServer = NSDate(timeIntervalSinceNow:timeinterval)
let outFormatter = DateFormatter()
outFormatter.locale = Locale(identifier: "en_Al")
print(dateFromServer)
let dateFormater = outFormatter
outFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
print(dateFormater.string(from: dateFromServer as Date))
let dateFromServers = dateFormater.string(from: dateFromServer as Date)
uj5u.com熱心網友回復:
LastCommunicationDate 是一個字串,但您將其轉換為 Double。試試這個:
let lastCommunicationDate = "2022-01-21T10:58:21.367"
//Create dateformatter to convert string to Date
let isoDateFormatter = ISO8601DateFormatter()
isoDateFormatter.formatOptions = [
.withFullDate,
.withTime,
.withColonSeparatorInTime,
.withFractionalSeconds
]
let isoDateFormatter2 = ISO8601DateFormatter()
isoDateFormatter2.formatOptions = [
.withFullDate,
.withTime,
.withColonSeparatorInTime
]
let date = isoDateFormatter.date(from: lastCommunicationDate) ?? isoDateFormatter2.date(from: lastCommunicationDate)
//Create dateformatter to format date for output
let outFormatter = DateFormatter()
outFormatter.locale = Locale(identifier: "en_Al")
outFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateFromServers = outFormatter.string(from: date!)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/420333.html
標籤:
