extract date ranges grouped by day from time intervals

爱⌒轻易说出口 提交于 2019-12-12 01:14:19

问题


I want to extract date ranges grouped by day from 2 time intervals. For exemple, from:

let startDateTimeInterval: NSTimeInterval = 1462060790  // "2016-04-30 23:59:50 +0000\n"
let endDateTimeInterval: NSTimeInterval = 1462183200 // "2016-05-02 00:00:10 +0000\n"

I want to get:

9 seconds // "[2016-04-30 23:59:50 => 2016-04-30 23:59:59]
86399 seconds // "[2016-05-01 00:00:00 => 2016-05-01 23:59:59]
10 seconds // "[2016-05-02 00:00:00 => 2016-05-01 00:09:59]

I accomplished it but I am wondering if there is a nicer solution. My methodology is :

1- Create NSDate from startDateTimeInterval
2- Create NSDate for end of day (23:59:59) from startDate (previous step)
3- Get difference between these 2 dates.
4- increment startDateTimeInterval with difference in seconds (previous step) and go back to step 1 with updated startDateTimeInterval. 

Repeat steps while startDate < endDate

Here is my code:

func createItemsPerDay(startDateTimeInterval: NSTimeInterval, endDateTimeInterval: NSTimeInterval)
{
    var currentTimeInterval = startDateTimeInterval
    let currentDate = NSDate(timeIntervalSince1970: currentTimeInterval)
    var currentDateEndOfDay = currentDate.endOfDay(NSTimeZone(forSecondsFromGMT: 0))

    if (currentDateEndOfDay.timeIntervalSince1970 > endDateTimeInterval) {
        currentDateEndOfDay = NSDate(timeIntervalSince1970: endDateTimeInterval)
    }

    let numberOfElapsedSecondsForEvent = currentDateEndOfDay.timeIntervalSinceDate(currentDate)

    print("event: \(numberOfElapsedSecondsForEvent) seconds")

    currentTimeInterval += (numberOfElapsedSecondsForEvent + 1)

    if (currentTimeInterval < endDateTimeInterval) {
        createItemsPerDay(startDateTimeInterval: currentTimeInterval, endDateTimeInterval: endDateTimeInterval)
    }
}

Do you have a suggestion?

Thanks!


回答1:


I would suggest the following solution.

import Foundation

func timeIntervalsPerDay(start: NSDate, _ end: NSDate, calendar: NSCalendar) -> [NSTimeInterval] {
    var timeIntervals = [NSTimeInterval]()
    let dayStart = NSDateComponents()
    dayStart.hour = 0
    dayStart.minute = 0
    dayStart.second = 0
    var prevDate = start
    calendar.enumerateDatesStartingAfterDate(start, matchingComponents: dayStart, options: [.MatchStrictly]) { date, exactMatch, _stop in
        let stop = date.map { $0.compare(end) != .OrderedAscending } ?? false
        if let date = date where !stop {
            timeIntervals.append(date.timeIntervalSinceDate(prevDate))
            prevDate = date
        }
        _stop.memory = ObjCBool(stop)
    }
    timeIntervals.append(end.timeIntervalSinceDate(prevDate))
    return timeIntervals
}

let df = NSDateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let start = df.dateFromString("2016-04-30 23:59:50 +0000")!
let end   = df.dateFromString("2016-05-02 00:00:10 +0000")!

let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
calendar.timeZone = NSTimeZone(name: "UTC")!

print(timeIntervalsPerDay(start, end, calendar: calendar)) // [10.0, 86400.0, 10.0]

Using NSCalendar is a more reliable approach then direct operating on NSTimeInterval, because calendar will count some anomalies like the leap second, etc.



来源:https://stackoverflow.com/questions/36994654/extract-date-ranges-grouped-by-day-from-time-intervals

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