Four years ago I introduced Time 0.9.0. It is appropriate that today, on its first birthday, it finally graduates to 1.0.0
!
Time is a package that provides extensive functionality for performing date and time calculations. It is built with safety and convenience in mind, so that "correct" calculations are easy, and "wrong" operations are either not possible (thanks to Swift's type system) or throw an error.
Time is available on Github, and its extensive documentation is hosted at the Swift Package Index.
Here's a brief overview of what Time can do for you:
// get the current device time:
let instantaneousNow = Clocks.system.now
// get the current calendar minute, a "Fixed<Minute>":
let currentMinute = Clocks.system.currentMinute
// round the current minute to the nearest quarter-hour:
let quarterHour = currentMinute.roundedToNearestMultiple(of: .minutes(15))
// advance the quarter hour by two months (accurate to the minute):
let thisTimeInTwoMonths = quarterHour + .months(2)
// from the quarter hour, get its calendar day:
let today = currentMinute.fixedDay
// get a Sequence of all the hours in the day:
let hours = today.hours
// print information about the hours in the day:
for hour in hours {
// there are many ".format(...)" methods to handle just about any use-case
print(hour.format(date: .medium, time: .long))
}
// be notified about the next 10 clock seconds:
for try await aSecond in Clocks.system.strike(every: Second.self).asyncValues.prefix(10) {
let formatted = aSecond.format(year: .naturalDigits, month: .naturalName, day: .naturalDigits, weekday: .naturalName, hour: .naturalDigits, minute: .twoDigits, second: .twoDigits)
print("The time is now: ", formatted)
}
All "fixed values" keep track of their calendar, locale, and time zone, enabling you to easily work with calendar values from around the world with the knowledge that their relative calculations are correct.
Beyond this, Time has numerous other capabilities, including:
- Creating clocks in any combination of calendar, locale, or time zone
- Creating clocks that move faster or slower than real time to facilitate testing time-dependent code
- Adopting the
RegionalClock
protocol to create your own clocks for controlling time - Listening for time changes via a Combine publisher or AsyncSequence
- Retrieving the
Range<Instant>
for any calendar value - Converting calendar values between time zones, locales, and calendars
- Truncating calendar values to get their containing units
- Finding differences between calendar values
- Offsetting (adjusting) calendar values by specific amounts
- And so much more!