根据今天的日期计算一天的StartDate和endDate。斯威夫特2

时间:2016-03-28 13:50:18

标签: swift timezone 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("Start of Day = \(rangeOfPeriod(.Day, date: NSDate()).0), End of Day = \(rangeOfPeriod(.Day, date: NSDate()).1)")

我得到以下内容,其中开始和结束日期比预期落后1小时:

Start of Day = 2016-03-27 23:00:00 +0000, End of Day = 2016-03-28 22:59:59 +0000

我期待的时候:

Start of Day = 2016-03-28 00:00:00 +0000, End of Day = 2016-03-28 23:59:59 +0000

任何帮助将不胜感激

0 个答案:

没有答案