Skip to content

Instantly share code, notes, and snippets.

@macshome
Last active February 29, 2024 17:06
Show Gist options
  • Save macshome/0db802a1aa378373b8e96c53cf5d9649 to your computer and use it in GitHub Desktop.
Save macshome/0db802a1aa378373b8e96c53cf5d9649 to your computer and use it in GitHub Desktop.
A simple extension to TimeInterval that allows you to just use the standard units of time rather than all that 60 * 60 jazz with APIs that use TimeInterval.
import Foundation
extension TimeInterval {
var seconds: TimeInterval { self }
var minutes: TimeInterval { self * 60 }
var hours: TimeInterval { self * 3_600 }
var days: TimeInterval { self * 86_400 }
var weeks: TimeInterval { self * 604_800 }
var months: TimeInterval { self * 2_628_000 }
static func minutes(_ numberOfMinutes: Int) -> TimeInterval {
60 * Double(numberOfMinutes)
}
}
print("42 seconds == \(42.seconds) seconds. Duh.")
print("1138 minutes == \(1138.minutes) seconds")
print("119 hours == \(119.hours) seconds")
print("9 days == \(9.days) seconds")
print("1 weeks == \(1.weeks) seconds")
print("11 months == \(11.months) seconds")
@macshome
Copy link
Author

macshome commented Feb 29, 2024

Sample playground output:

42 seconds == 42.0 seconds. Duh.
1138 minutes == 68280.0 seconds
119 hours == 428400.0 seconds
9 days == 777600.0 seconds
1 weeks == 604800.0 seconds
11 months == 28908000.0 seconds

Sample usage:
Date(timeIntervalSinceNow: 22.days + 8.hours)

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