Home
Map
Date Examples (TimeInterval)Use the Date type from Foundation to compute the current date, and add TimeIntervals to dates.
Swift
This page was last reviewed on Jan 16, 2024.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 16, 2024 (edit link).
Home
Changes
© 2007-2024 Sam Allen.