NSDateComponents weekOfYear 返回错误的日期 [英] NSDateComponents weekOfYear returns wrong date
本文介绍了NSDateComponents weekOfYear 返回错误的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我正在制作一个基本的周选择器,您可以在其中选择周数和年份,并从周开始点获取相应的日期.
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.
基本测试场景
let calendar = NSCalendar.currentCalendar()
let components = NSDateComponents()
components.year = 2015
components.weekOfYear = 15
print(calendar.dateFromComponents(components)!)
你可以看到,我将通缉年份设置为 2015 年,通缉周设置为 15,但我得到的结果是:2014-12-31 23:00:00 +0000"
You can see, that i set the wanted year to 2015 and the wanted week to 15, but the result i get is: "2014-12-31 23:00:00 +0000"
...这真的让我很困惑.无论我选择哪一周和哪一年,它都会在 12 月关闭.
... and thats really gets me hanging. No matter what week and year i choose, it will always be off and in december.
预先感谢您的帮助.
推荐答案
weekOfYear
与 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
<小时>
Swift 3 及更高版本的更新:
let calendar = Calendar.current
var components = DateComponents()
components.yearForWeekOfYear = 2015
components.weekOfYear = 15
print(calendar.date(from: components)!)
这篇关于NSDateComponents weekOfYear 返回错误的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文