Swift Date and TimeInterval: A Primer

How to use Date, DateComponents and TimeInterval in Swift

Carlos Farini
The Mobile Mindset
4 min readMar 19, 2020

--

Photo by Fabian Albert on Unsplash

I recently made an app called Trade Tycoon that uses real-time data from the New York Stock Exchange to simulate stock trading. The objective for the player is to make the most profit from trading, and for me, it is to provide users that want to learn to trade stocks with a way to drive up their confidence to enter the real market.

I am (re)using some blocks of code from this app, to showcase real-life examples that use the Swift Date type, and some common usage cases.

This article covers some Date calculations with Swift used to verify if a date falls on a holiday, and shows how to implement an update system that needs to refresh some information every x amount of time. The system does this by looking at a file’s lastModified property to determine whether the update should occur.

In this article I am covering some of the following Swift types:

  • Date
  • DateComponents
  • Calendar
  • TimeInterval
  • Double

One of the first blocks of code in the development of this app was performing a function to check whether the stock market was open, or not. The logic behind this would be to define when orders can be placed — if a user places an order to buy a stock when the stock market is closed, that order can’t be filled until the market opens.

To tell if the stock market was open, I first checked the business hours at which the stock market works, which can be found on the NYSE site and includes holidays and trading hours.

The idea is to build that table of dates in code.

Note that we have to take into account the fact that the NYSE is in a TimeZone and a user can be in any TimeZone in the world. Luckily, Apple thought about letting each app define its own default TimeZone.

The first attempt to establish the status of the US stock market

So far we have checked for weekends, and when it is not a weekend, we check for the business hours, but we are still not done. We haven’t checked for holidays yet.

This is a great opportunity to use an extension of Date.

Checking whether a date is a holiday

Biz Status

The stock market might have an open or closed status, and thus, we return a Boolean value from the first function above. However, that doesn’t account for other statuses such as after hours, or holiday day off, etc.

To define the status of NYSE, I have created this enum.

An enum representing the status of the NYSE

In this enum, the holiday case takes a string as an argument, making it easy to pass the name of the holiday, in case it needs to be displayed.

Now we can go back and improve our function that checks if the market is open and change the return type to the enum created above.

Note that one can also use this function as an extension of Date, but in this case, separation of concerns is a better approach. When you are coding a stock market simulator, there are going to be plenty of opportunities to use Date extensions.

Notice that some holidays are celebrated on another day when they fall on a weekend. That is called holiday observed as the NYSE website explains.

Bonus rocket science

Perhaps you have noticed that we are not checking Good Friday — The first Friday after Sunday Easter. The reason is that Easter is a very complicated holiday to be calculated. It requires some rocket science type of calculations. Feel free to google “Computus”, or check this out on Wikipedia.

TimeInterval

Another way to handle Dates in Swift is by using TimeInterval. An example application of TimeInterval is one where the code needs to establish whether a file needs to be updated.

In Trade Tycoon’s case, there is a “News” part of the app where the code waits for a file to turn 24 hours old before it refreshes the data. It looks at the Date that the file containing the articles was last modified to decide if it needs to fetch new articles.

To access the Date the file was last modified, and also the Date it was first created, I wrote this function:

Getting the lastModified and first-created date from a File info, in Swift

One of the great things about TimeInterval is that it is a type alias of Double, which means you can compare them easily. Now we code in how often the system should update the news (i.e., 60 seconds * 60 minutes * 24 hours), which will be the number of seconds in 24 hours. This is known as a Double type, and is compared with the TimeInterval (also in seconds) between the current Date() and when the file was last updated.

The code checks if the file was last modified recently enough, and otherwise it will fetch new articles.

Last, but not least, DateComponents can also be used as the amount of time that passed between one Date and another. Here is an example:

Conclusion

There are many ways of handling the Date type in Swift, as well as many uses for it. I am glad to share some cases where a few of these methods are used, and also curious to know about other uses for Date, so feel free to leave a comment.

--

--