Skip to content

Instantly share code, notes, and snippets.

@algal
Created November 28, 2015 04:09
Show Gist options
  • Save algal/8ee7cc0ea098b9b9dd6f to your computer and use it in GitHub Desktop.
Save algal/8ee7cc0ea098b9b9dd6f to your computer and use it in GitHub Desktop.
NSDate extensions for time measured from system restart
/// seconds from the reference date to the system's last restart
private let secondsFromReferenceDateToRestart:NSTimeInterval = {
/* we pretend these next two statements take place atomically, although in fact they do not, and the fact that clock progresses between the two statements will introduce miniscule error into our calculation */
let secondsFromSystemRestartToInit = NSProcessInfo().systemUptime
let secondsFromReferenceDateToInit = NSDate.timeIntervalSinceReferenceDate()
let retVal = secondsFromReferenceDateToInit - secondsFromSystemRestartToInit
return retVal
}()
extension NSDate {
/**
Returns an `NSDate` intialized relative to the moment of the sytem's last restart, as reported by `NSProcessInfo.systemUptime`.
- parameter timeIntervalSinceSystemRestart: seconds from the system's restart until the moment we want the new object to represent.
*/
convenience init(timeIntervalSinceSystemRestart ti:NSTimeInterval) {
let secondsFromRestartToNow = ti
let timeFromReferenceDateToNow = secondsFromReferenceDateToRestart + secondsFromRestartToNow
self.init(timeIntervalSinceReferenceDate:timeFromReferenceDateToNow)
}
/**
seconds from the system's last restart to the moment represented by the current receiver
*/
public var timeIntervalSinceRestart: NSTimeInterval {
let secondsFromReferenceDateToThisMoment = self.timeIntervalSinceReferenceDate
let secondsFromRestartToThisMoment = secondsFromReferenceDateToThisMoment - secondsFromReferenceDateToRestart
return secondsFromRestartToThisMoment
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment