Created
April 12, 2017 18:46
-
-
Save prachigauriar/c42a75806d3ab3b8ec2e11586b70ccc6 to your computer and use it in GitHub Desktop.
Calendrical Calculations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension Calendar { | |
func startOfNextDay(for date: Date) -> Date? { | |
let start = startOfDay(for: date) | |
return self.date(byAdding: .day, value: 1, to: start) | |
} | |
func endOfDay(for date: Date) -> Date? { | |
let start = startOfDay(for: date) | |
let components = DateComponents(day: 1, nanosecond: -1000000) | |
return self.date(byAdding: components, to: start) | |
} | |
} | |
func randomDate() -> Date { | |
let fiveYearsInSeconds = 5 * 365 * 24 * 3600 | |
let timeInterval = Double(arc4random_uniform(UInt32(fiveYearsInSeconds))) * (arc4random_uniform(2) == 0 ? 1 : -1) | |
return Date(timeInterval: timeInterval, since: Date()) | |
} | |
func timeBlock(_ block: () -> Void) -> TimeInterval { | |
let start = Date() | |
block() | |
return Date().timeIntervalSince(start) | |
} | |
let calendar = Calendar(identifier: .gregorian) | |
var startOfDayTime: TimeInterval = 0 | |
var startOfNextDayTime: TimeInterval = 0 | |
var endOfDayTime: TimeInterval = 0 | |
let iterationCount = 10000 | |
for _ in 0 ..< iterationCount { | |
let date = randomDate() | |
startOfDayTime += timeBlock { | |
_ = calendar.startOfDay(for: date) | |
} | |
startOfNextDayTime += timeBlock { | |
_ = calendar.startOfNextDay(for: date) | |
} | |
endOfDayTime += timeBlock { | |
_ = calendar.endOfDay(for: date) | |
} | |
} | |
print("Iteration count = \(iterationCount)") | |
print("Time interval for startOfDay(for:) = \(startOfDayTime)") | |
print("Time interval for startOfNextDay(for:) = \(startOfNextDayTime)") | |
print("Time interval for endOfDay(for:) = \(endOfDayTime)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: