Home
Swift
Date Examples (TimeInterval)
Updated Jan 16, 2024
Dot Net Perls
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.
ContinuousClock
Example. 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.
Part 1 We can get the current date (now) by accessing the Date.now property. Alternatively we can use Date() with no arguments.
Part 2 Suppose we want a date before "now." We can use the Date init with timeIntervalSinceNow and a negative number of seconds.
Part 3 We can get a relative date after another date by using the Date() with timeInterval and since.
Part 4 We can add a TimeInterval to a Date. The Date is mutated and now represents a date 1000 seconds later in time.
Part 5 We can use 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 example. We 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 16, 2024 (edit link).
Home
Changes
© 2007-2025 Sam Allen