生成月份的开始和结束。斯威夫特2

时间:2016-03-23 14:08:00

标签: swift nsdate nscalendar nstimeinterval

我有以下代码:

func rangeOfPeriod(period: NSCalendarUnit, date: NSDate) -> (NSDate, NSDate) {
        let calendar = NSCalendar.currentCalendar()
        var startDate: NSDate? = nil
        var duration: NSTimeInterval = 0

        calendar.rangeOfUnit(period, startDate: &startDate, interval: &duration, forDate: date)

        let endDate = startDate!.dateByAddingTimeInterval(duration - 1)

        return (startDate!, endDate)
}

当我打印以下行时:

print("Day test = \(rangeOfPeriod(.Day, date: NSDate()))")
print("Week test = \(rangeOfPeriod(.WeekOfYear, date: NSDate()))")
print("month test = \(rangeOfPeriod(.Month, date: NSDate()))")
print("Year test = \(rangeOfPeriod(.Year, date: NSDate()))")

除月份之外,所有这些都按预期工作。

我得到'月份测试=(2016-03-01 00:00:00 +0000,2016-03-31 22:59:59 +0000)'结果,似乎缺少一个小时。对于所有其他人来说,我得到'2016-03-26 23:59:59 +0000'。

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

可能对interval方法中的rangeOfUnit参数存在疑惑。

来自文档

func rangeOfUnit(_ unit: NSCalendarUnit,
        startDate datep: AutoreleasingUnsafeMutablePointer<NSDate?>,
           interval tip: UnsafeMutablePointer<NSTimeInterval>,
           forDate date: NSDate) -> Bool
     

.....

     

提示:返回时,包含日历单元NSTimeInterval的持续时间(unit)   包含日期date

由于夏令时更改,本月(2016年3月)的持续时间为

31 * 86400.0 - 3600.0 = 2674800.0 

这意味着缺少一个小时,但是没有指定。

要获得月末,这是更准确的

func endOfThisMonth() -> NSDate
{
  let calendar = NSCalendar.currentCalendar()
  let components = NSDateComponents()
  components.day = 1
  let startOfNextMonth = calendar.nextDateAfterDate(NSDate(), matchingComponents: components, options: .MatchNextTime)!
  return calendar.dateByAddingUnit(.Second, value: -1, toDate: startOfNextMonth, options: [])!
}