Date
As part of Foundation, the Date
type in Swift can be used to accurately represent dates. It can be used with TimeInterval
, which represents periods of time.
By adding TimeInterval
to specific dates, we can get new dates. By adding the seconds in a day to a Date
, we can get tomorrow. And with negative seconds, we can get yesterday.
Here we demonstrate creating dates, and then adding seconds to them with TimeInterval
. The Date
init()
function is used, and one of the dates is mutated.
Date.now
property. Alternatively we can use Date()
with no arguments.Date
init
with timeIntervalSinceNow
and a negative number of seconds.Date()
with timeInterval
and since.TimeInterval
to a Date
. The Date
is mutated and now represents a date 1000 seconds later in time.addTimeInterval
to a date instead of the addition operation. The effect is the same.import Foundation // Part 1: get current date. let now = Date.now print(now) // Part 2: some time before now. let start = Date(timeIntervalSinceNow: -10000) print(start) // Part 3: some time after. var after = Date(timeInterval: 5000, since: start) print(after) // Part 4: add a time interval to the date. after += TimeInterval(1000) print(after) // Part 5: add another time interval. after.addTimeInterval(1000) print(after)2023-09-20 17:03:26 +0000 2023-09-20 14:16:46 +0000 2023-09-20 15:40:06 +0000 2023-09-20 15:56:46 +0000 2023-09-20 16:13:26 +0000
Func
exampleWe can pass a Date
to a function, and return a Date
as well. Here we implement a simple function that computes yesterday based on its argument.
import Foundation func getYesterday(now: Date) -> Date { var result = now // 60 seconds per minute, 60 minutes per hour, 24 hours per day result += TimeInterval(-(60 * 60 * 24)) return result } // Compute yesterday based on today. print("TODAY: ", Date.now) print("YESTERDAY:", getYesterday(now: Date.now))TODAY: 2023-09-20 17:10:41 +0000 YESTERDAY: 2023-09-19 17:10:41 +0000
By using the built-in Date
type from Foundation, we can represent dates and mutate them. TimeInterval
lets us add and subtract seconds from a Date
.