使用NSCalendar将日期添加到日期

时间:2015-10-28 22:45:41

标签: ios swift nsdate swift2 nscalendar

我正在尝试为另一个人添加一天(它完美无缺,直到我看到一些东西)。

2016年第6周(从1月30日开始),如果我有一天到这个日期,它会显示我2015年12月31日。

你能解释一下我做错了吗?

这是代码(你可以把它放在游乐场):

let weekToDisplay = 6
let yearToDisplay = 2016

let calendar = NSCalendar.currentCalendar()
let comp = NSDateComponents()
comp.weekday = calendar.firstWeekday
comp.weekOfYear = weekToDisplay
comp.year = yearToDisplay

let dateToIncrement = calendar.dateFromComponents(comp)! // "Jan 31, 2016, 12:00 AM
var incrementedDate = calendar.dateByAddingUnit(.Day, value: 1, toDate: dateToIncrement, options: NSCalendarOptions.WrapComponents)! // "Jan 1, 2016, 12:00 AM"

print(dateToIncrement) // "2016-01-30 23:00:00 +0000\n"
print(incrementedDate) // "2015-12-31 23:00:00 +0000\n"

最后一件事,当您打印日期时,它与执行特定代码行时在操场上显示的不一样,为什么? (见评论)

2 个答案:

答案 0 :(得分:1)

您的问题是包装日期组件的选项。你不想要那个。只需:

let weekToDisplay = 6
let yearToDisplay = 2016

let calendar = NSCalendar.currentCalendar()
let comp = NSDateComponents()
comp.weekday = calendar.firstWeekday
comp.weekOfYear = weekToDisplay
comp.year = yearToDisplay

let dateToIncrement = calendar.dateFromComponents(comp)! // "Jan 31, 2016, 12:00 AM
var incrementedDate = calendar.dateByAddingUnit(.Day, value: 1, toDate: dateToIncrement, options: [])! // "Jan 1, 2016, 12:00 AM"

print(dateToIncrement)
print(incrementedDate)

答案 1 :(得分:0)

要解决您的问题,请转到:

let weekToDisplay = 6
let yearToDisplay = 2016

let calendar = NSCalendar.currentCalendar()
let comp = NSDateComponents()
comp.weekday = calendar.firstWeekday
comp.weekOfYear = weekToDisplay
comp.year = yearToDisplay

let dateToIncrement = calendar.dateFromComponents(comp)! // "Jan 31, 2016, 12:00 AM

print(dateToIncrement) // "2016-01-30 23:00:00 +0000\n"


let incrementedDate = calendar.dateByAddingUnit(.Day, value: 1, toDate: dateToIncrement, options: .MatchStrictly) // "Feb 1, 2016, 12:00 AM"