首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用DateComponents返回错误日期初始化weekOfMonth

用DateComponents返回错误日期初始化weekOfMonth
EN

Stack Overflow用户
提问于 2022-09-30 09:46:31
回答 1查看 59关注 0票数 0

以下是代码:

代码语言:javascript
运行
复制
let components = DateComponents(year: 2022,month: 9,weekOfMonth: 3)
let date = Calendar.autoupdatingCurrent.date(from: components)!
let formatter = DateFormatter()
formatter.dateStyle = .long
formatter.timeStyle = .none
print(formatter.string(from: date))

这是输出:

September 1, 2022

但正确的答案应该是September 11, 2022。为什么?这是窃听器还是我漏掉了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-30 18:12:03

此方法将创建给定年份、月份和周的开始日期。如果一周的开始日期不在指定的月份,则此值将返回零:

代码语言:javascript
运行
复制
func startOfWeek(in year: Int, month: Int, week: Int, calendar: Calendar = Calendar(identifier: .iso8601)) -> Date?{
    //You would need to set this calendar according when your week starts.
    //For me it´s monday so I need .iso8601
    //For sunday set it to gregorian
    
    var components = DateComponents(calendar: calendar, year: year, month: month, weekOfMonth: week )
    
    //Get the first day of the month. This will probably never fail but....
    guard let firstOfMonth = components.date else{
        return nil
    }
    
    // Handling edge case first of month is start of week
    // if the first is a monday and we look for the first return it
    let startOfWeek = calendar.dateComponents([.calendar, .yearForWeekOfYear, .weekOfYear], from: firstOfMonth).date
    if startOfWeek == firstOfMonth, week == 1{
        return firstOfMonth
    }
    // else just ommit the additional week and move on
    else if startOfWeek == firstOfMonth {
        components = DateComponents(calendar: calendar, year: year, month: month, weekOfMonth: week)
    }
    
    // search for the next date starting at first of month according to components given
    return calendar.nextDate(after: firstOfMonth, matching: components, matchingPolicy: .nextTime)
}

大多数代码应该是不言自明的。

测试:

代码语言:javascript
运行
复制
let dates = [(2022, 1, 2), (2022, 2, 1), (2022, 3, 4), (2022, 8, 1), (2022, 9, 1), (2022, 9, 2), (2022, 9, 3), (2022, 9, 4), (2022, 12, 4) , (2021, 11, 5)]

let formatter = DateFormatter()
formatter.dateFormat = "dd MM yyyy"

dates.forEach { year, month, week in
    let date = startOfWeek(in: year, month: month, week: week, calendar: Calendar(identifier: .gregorian))
    print(date != nil ? formatter.string(from: date!) : "no date found")
}

输出:

代码语言:javascript
运行
复制
02 01 2022
no date found
20 03 2022
no date found
no date found
04 09 2022
11 09 2022 <-- thrid week in september 2022
18 09 2022
18 12 2022
28 11 2021
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73906873

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档