Calculating StartDate and endDate of a day based on todays date. Swift 2

拜拜、爱过 提交于 2020-01-07 02:35:30

问题


I have the following function which i am using to calculate a start and end of todays date. It was working perfectly last week, i think it may have something to do with the clocks going forwards?

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)
}

When I try and calculate the start and end of a day using:

print("Start of Day = \(rangeOfPeriod(.Day, date: NSDate()).0), End of Day = \(rangeOfPeriod(.Day, date: NSDate()).1)")

I get the following, where the start and end date is 1hour behind what is expected:

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

when i would expect:

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

Any help would be appreciated

来源:https://stackoverflow.com/questions/36263743/calculating-startdate-and-enddate-of-a-day-based-on-todays-date-swift-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!