NSDateComponents weekOfYear returns wrong date

后端 未结 1 373
独厮守ぢ
独厮守ぢ 2020-12-20 07:22

so i am making a basic week picker, where you can pick a week number and year, and get the corresponding date from the weeks startpoint.

A basic test scenario

<
相关标签:
1条回答
  • 2020-12-20 07:47

    weekOfYear works in conjunction with yearForWeekOfYear:

    let calendar = NSCalendar.currentCalendar()
    let components = NSDateComponents()
    
    components.yearForWeekOfYear = 2015
    components.weekOfYear = 15
    
    print(calendar.dateFromComponents(components)!)
    // 2015-04-05 22:00:00 +0000
    

    Update for Swift 3 and later:

    let calendar = Calendar.current
    var components = DateComponents()
    
    components.yearForWeekOfYear = 2015
    components.weekOfYear = 15
    
    print(calendar.date(from: components)!)
    
    0 讨论(0)
提交回复
热议问题