我正在嘗試將 a 轉換Date為 a DateComponents,更改一些屬性并獲得新的Date回傳值。我撰寫了以下代碼:
import Foundation
var components = Calendar.current.dateComponents(in: .current, from: Date())
components.day = 7
components.month = 3
components.year = 1900
DateFormatter.localizedString(from: components.date!, dateStyle: .long, timeStyle: .long)
我已經America/Denver在 iOS 15.0 上的 iOS 模擬器上的時區/語言環境中以及運行最新的 macOS Big Sur 和 Xcode 13.0 的 Mac 上的 Swift REPL 中對此進行了測驗,并且在這兩個地方,我在以下位置獲得了大約以下輸出撰寫本文的時間:
March 7, 2021 at 9:38:13 AM MST
除了這一年之外,關于這一切的一切都在預料之中。我已經明確地將年份設定為1900,但輸出中的年份是2021。我如何DateComponents在生成日期時獲得榮譽年份,或者我如何手動做同樣的事情,這樣它才能真正起作用?
uj5u.com熱心網友回復:
如果你得到所有從一個日期組件dateComponents(in:from:),你必須設定也yearForWeekOfYear相應
components.yearForWeekOfYear = 1900
或僅指定的日期和時間組件,包括calendar和timeZone你真正需要的,例如
var components = Calendar.current.dateComponents([.calendar, .timeZone, .year, .month, .day, .hour, .minute, .second], from: Date())
components.day = 7
components.month = 3
components.year = 1900
DateFormatter.localizedString(from: components.date!, dateStyle: .long, timeStyle: .long)
uj5u.com熱心網友回復:
請注意,您正在獲取所有日期組件,包括weekOfYear, weekOfMonth, dayOfWeek,最重要的是,yearForWeekOfYear. 當您將日期組件設定為 1900-03-07 時,您也沒有正確設定所有這些組件,并且當Date從DateComponents具有此類沖突組件的a決議 a 時,演算法恰好更喜歡它們從yearForWeekOfYear.
如果您將這些欄位設定為nil,您將獲得預期的結果:
var components = Calendar.current.dateComponents(in: .current, from: Date())
components.day = 7
components.month = 3
components.year = 1900
components.yearForWeekOfYear = nil
盡管如此,日期組件中仍然會存在沖突,雖然這不會導致崩潰,但我不確定這種行為將來是否會改變。我建議您只獲取所需的組件。例如:
var components = Calendar.current.dateComponents([
.calendar, .timeZone, .era, .year, .month, .day, .hour, .minute, .second, .nanosecond
], from: Date())
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/334414.html
