Skip to content

Instantly share code, notes, and snippets.

@prachigauriar
Created April 12, 2017 18:46
Show Gist options
  • Save prachigauriar/c42a75806d3ab3b8ec2e11586b70ccc6 to your computer and use it in GitHub Desktop.
Save prachigauriar/c42a75806d3ab3b8ec2e11586b70ccc6 to your computer and use it in GitHub Desktop.
Calendrical Calculations
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)")
@prachigauriar
Copy link
Author

Output:

Iteration count = 10000
Time interval for startOfDay(for:) = 2.34334194660187
Time interval for startOfNextDay(for:) = 6.10344672203064
Time interval for endOfDay(for:) = 8.15246593952179

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment