我有一个功能:

internal func startOfNextMonth() -> NSDate? {
    guard
        let cal: NSCalendar = NSCalendar.currentCalendar(),
        let comp: NSDateComponents = NSDateComponents() else { return nil }
    comp.month = 1
    comp.day = 0
    comp.to12pm()
    let date = cal.dateByAddingComponents(comp, toDate: self.startOfMonth()!, options: [])!
    return date
}

这应该计算下个月的第一天,但是它返回2016-03-02 08:00:00 UTC
这和闰年(2月29日搞砸了)有关吗
以下是我的startOfMonth函数作为参考,以及to12pm()扩展:
internal func startOfMonth() -> NSDate? {
    guard
        let cal: NSCalendar = NSCalendar.autoupdatingCurrentCalendar(),
        let comp: NSDateComponents = cal.components([.Year, .Month], fromDate: self.at12pm()!) else { return nil }
    comp.to12pm()
    return cal.dateFromComponents(comp)!
}

internal extension NSDateComponents {
    func to12pm() {
        self.hour = 12
        self.minute = 0
        self.second = 0
    }
}

internal func at12pm() -> NSDate? {
    let cal = NSCalendar.currentCalendar()
    return cal.dateBySettingHour(12, minute: 0, second: 0, ofDate: self, options: [])
}

最佳答案

startOfMonth()将在下个月的第一天下午12点(12:00)返回,然后在startOfNextMonth()中再添加12小时,此结果将提前一天返回。
NSCalendar有一个聪明的方法来计算下个月的开始时间,而不考虑夏令时的变化或其他不规则情况

let calendar = NSCalendar.currentCalendar()
let components = NSDateComponents()
components.day = 1
let startOfNextMonth = calendar.nextDateAfterDate(NSDate(), matchingComponents: components, options: .MatchNextTime)

09-04 23:27