简体   繁体   English

Swift - 获取 DateComponents 条目的 weekOfYear

[英]Swift - Get weekOfYear for a DateComponents entry

I'm facing some problems to get the weekOfYear for a valid DateComponents value.我在获取有效 DateComponents 值的 weekOfYear 时遇到了一些问题。 This code这段代码

let cal = Calendar.current
let dc = DateComponents(calendar:cal, year: 2023, month: 1, day:12)
let woy = dc.weekOfYear

print("Week of year: \(woy)")

generates产生

Week of year: nil

as an output.作为 output。

I've expected 2 ...我预计2 ...

DateComponents is a simple type. DateComponents是一种简单类型。 It is merely a collection of date components.它只是日期组件的集合。 It does not do date computations like calculating the week of year.它不会像计算一年中的星期那样进行日期计算。 That's the job of Calendar .那是Calendar的工作。 You did not give it a week of year when you initialise the date components, so you get nil when you ask for it.当你初始化日期组件时,你没有给它一年中的一周,所以当你要求它时你得到nil

You can ask the calendar to make a Date out of the DateComponents you have, and ask it what the week of year is:您可以要求日历从您拥有的DateComponents中创建一个Date ,并询问它一年中的星期几:

let cal = Calendar.current
let dc = DateComponents(calendar:cal, year: 2023, month: 1, day:12)
if let date = cal.date(from: dc) {
    // prints 2 as expected
    print(cal.component(.weekOfYear, from: date))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM