[英]How to get the current time in a specific timezone?
我目前正在開發一個應用程序,我需要在該應用程序中獲取歐洲/羅馬時區的當前日期和時間。 為此,我創建了以下方法:
static func getItalianDate() -> Date {
let timezone = TimeZone(identifier: "Europe/Rome")!
let seconds = TimeInterval(timezone.secondsFromGMT(for: Date()))
let date = Date(timeInterval: seconds, since: Date())
return date
}
但是,如果用戶從設置“常規”->“日期和時間”操縱日期和時區,並且我無法弄清楚如何獲得正確答案,這將不會返回正確的值。 我需要的格式類似於:“yyyy-MM-dd HH:mm:ss”。
有什么建議嗎?
編輯
我發現這個問題- 仍然沒有答案 - 與我在這里面臨的問題相同。 使用服務器是唯一可用的選項嗎?
let dateFormatter = {
var df = DateFormatter()
df.timeZone = Calendar.current.timeZone
df.dateFormat = ”yyyy-MM-dd HH:mm:ss”
return df
}()
let timestamp = dateFormatter.string(from: date)
// display your timestamp
如果您的應用程序需要在時區更改時刷新其視圖(因此重新計算要顯示的時間戳),則在基於 UIKit 的情況下響應 NSSystemTimeZoneDidChange 通知,或者在其視圖基於 SwiftUI 的情況下使用 SwiftUI 環境時區全局變量。
import Foundation
// 1. Choose a date
let today = Date()
// 2. Pick the date components
let hours = (Calendar.current.component(.hour, from: today))
let minutes = (Calendar.current.component(.minute, from: today))
let seconds = (Calendar.current.component(.second, from: today))
// 3. Show the time
print("\(hours):\(minutes):\(seconds)")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.