我需要通過一個切換顯示事件的日期/時間,讓用戶在當前時區和事件發生的時區之間切換。
我正在嘗試使用 SwiftUI 文本格式化程式,但無法弄清楚如何使其適用于備用時區。
所以我有一個簡單的格式化程式:
@State var localTimeZone: TimeZone?
let date: Date
var formatter: DateFormatter {
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy HH:mm:ss"
dateFormatter.timeZone = localTimeZone
return dateFormatter
}
然后我嘗試像這樣顯示日期,但似乎不一致。例如,為什么以下不同?我希望他們是一樣的。
// 'Correctly' displays formatted in the timezone passed in (eg 01/08/2022 23:25:00)
Text(formatter.string(from: net))
// 'Ignores formatter' and displays in the current timezone (eg 01/08/2022 21:25:00)
Text(net, formatter: formatter)
最終目標是能夠使用以下文本格式并具有可以切換 Date 物件的時區的開關。
Text(date, format: .dateTime.timeZone(.specificName(.long)))
Text(date, format: .dateTime.day().month().hour().minute().second())
這可能嗎,我似乎在這里畫了一個空白,任何正確方向的點將不勝感激!
如果它是相關的,我所擁有的事件的唯一詳細資訊是 lat/long 和 alpha 3 國家/地區代碼。我目前發現從中獲取任何型別時區的唯一方法是使用以下方法獲取地標(這就是我嘗試使用 TimeZone 的原因)。
func getTimeZone(location: CLLocation) async -> TimeZone? {
let geocoder = CLGeocoder()
do {
guard let placeMark = try await geocoder.reverseGeocodeLocation(location).first else { return nil }
return placeMark.timeZone
} catch {
print("Filed to get timeZone for event")
return nil
}
}
謝謝你的幫助!
更新:剛剛發現你可以設定.environment(\.timeZone, localTimeZone)
一個視圖,里面的所有東西都會相應地顯示出來。
例如...
Section("Local") {
Text(date, formatter: formatter)
}
.environment(\.timeZone, localTimeZone)
但是以下仍然不起作用
Section("Local") {
Text(date, format: .dateTime.timeZone(.specificName(.long)))
Text(date, format: .dateTime.day().month().hour().minute().second())
}
.environment(\.timeZone, localTimeZone)
uj5u.com熱心網友回復:
看看你的最終目標,你似乎只想改變 的timeZone
屬性Date.FormatStyle
,以便可以在不同的時區格式化日期。
您可以撰寫一個小擴展,以便您可以更方便地進行行內設定。
extension Date.FormatStyle {
func withTimeZone(_ timeZone: TimeZone) -> Date.FormatStyle {
var copy = self
copy.timeZone = timeZone
return copy
}
}
然后你可以做這樣的事情:
Text(date, format:
.dateTime.timeZone(.specificName(.long)).withTimeZone(localTimeZone)
)
Text(date, format:
.dateTime.day().month().hour().minute().second().withTimeZone(localTimeZone)
)
還可以考慮只使用一個Text
,其中包含時區、日期和時間的單一格式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/512853.html
上一篇:左右滑動后轉換集合視圖單元格容器