ios – 从weekOfYear获取不正确的开始和结束日期

前端之家收集整理的这篇文章主要介绍了ios – 从weekOfYear获取不正确的开始和结束日期前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
let calendar = Calendar.current
    var dateComponents = DateComponents()
    dateComponents.weekday = calendar.firstWeekday
    dateComponents.weekOfYear = 2
    dateComponents.year = 2017
    let startOfWeek = calendar.date(from: dateComponents)
    let endOfWeek = calendar.date(byAdding: .day,value: 6,to: startOfWeek!)
    let formatter = DateFormatter()
    formatter.dateStyle = .short
    print(formatter.string(from: startOfWeek!))
    print(formatter.string(from: endOfWeek!))

打印:

1/8/17
    1/14/17

改变代码

dateComponents.weekOfYear = 1
    dateComponents.year = 2017

打印:

12/31/17
    1/6/18

为什么是12/31/17?

有谁告诉我?非常感谢.

解决方法

当我使用.full样式打印日期时,我会在2017年12月31日星期日的第一个日期,但这显然是错误的,因为12月31日是星期四.

如果您想获得正确的日期,请使用yearForWeekOfYear而不是year. Docs

You can use the yearForWeekOfYear property with the weekOfYear and weekday properties to get the date corresponding to a particular weekday of a given week of a year. For example,the 6th day of the 53rd week of the year 2005 (ISO 2005-W53-6) corresponds to Sat 1 January 2005 on the Gregorian calendar.

另外,你可能有点顽皮而不听文档并使用weekOfYear = 54:

let calendar = Calendar.current
var dateComponents = DateComponents()
dateComponents.weekday = calendar.firstWeekday
dateComponents.weekOfYear = 54
dateComponents.year = 2017
let startOfWeek = calendar.date(from: dateComponents)
let endOfWeek = calendar.date(byAdding: .day,to: startOfWeek!)
let formatter = DateFormatter()
formatter.dateStyle = .short
print(formatter.string(from: startOfWeek!))
print(formatter.string(from: endOfWeek!))

这打印:

1/1/17
1/7/17

巧合的是,正确的日期.

原文链接:https://www.f2er.com/iOS/334025.html

猜你在找的iOS相关文章