快速设置日历单位月份会增加年份

时间:2016-09-06 13:30:21

标签: swift swift2

以下代码应该将当前年份设置为第一天:

import UIKit

private func getYearStartDate() -> NSDate {
    let calendar = NSCalendar.currentCalendar()

    var date = calendar.dateBySettingHour(0, minute: 0, second: 0, ofDate: NSDate(), options: [])
    date = calendar.dateBySettingUnit(.Month, value: 1, ofDate: date!, options: [])
    date = calendar.dateBySettingUnit(.Day, value: 1, ofDate: date!, options: [])

    return date!
}

print("startdate=\(getYearStartDate())")
print("enddate=\(NSDate())")

但是当我检查它时,该值设置为NEXT年的第一天。

我的结果:

startdate=2017-01-01 02:00:00 +0000
enddate=2016-09-06 13:44:06 +0000

我期待的结果:

startdate=2016-01-01 02:00:00 +0000
enddate=2016-09-06 13:44:06 +0000

1 个答案:

答案 0 :(得分:0)

nextDateAfterDate:matchingComponents:options:的方法NSCalendar更适合此目的,也可以向后搜索过去的1月1日:

let calendar = NSCalendar.currentCalendar()
let components = NSDateComponents()
components.month = 1
components.day = 1
let yearStartDate = calendar.nextDateAfterDate(NSDate(), 
                             matchingComponents: components, 
                                        options: [.MatchNextTime, .SearchBackwards])