Calculating StartDate and endDate of a day based o

2019-09-01 03:13发布

问题:

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