Working with Dates in Swift

Stephen Feuerstein Tutorials

It’s inevitable that at some point in your development career you’ll need to work with dates. Maybe you’re showing a feed of posts à la Facebook, or the upcoming schedule of your favorite sports team. While dates are easy conceptually, they aren’t so easy when you’re writing code for formatting and displaying them.

The Date Struct

The iOS SDK’s Foundation framework has a super convenient struct called Date (real original) that makes working with, you guessed it, dates much easier.

Today’s Date

Getting today’s date, or more accurately the date and time right now, couldn’t be simpler. All you need to do is create an instance of the Date struct and you’re good to go!

A Future Date

You don’t always want to work with today’s date though. Sometimes you need a Date struct that represents tomorrow, or even a few days later. For that, there are a couple of handy convenience initializers on the Date struct.

You may be wondering where that 86400 number came from. TimeIntervals are measured in seconds, so in order to use timeIntervalSinceNow and timeInterval:since: we had to convert the number of days to seconds. For figuring out the number of seconds in a day there are 60 seconds in a minute, 60 minutes in an hour, and 24 hours in a day so we take 60 * 60 * 24 = 86400.

You can find out more about the Date struct in Apple’s documentation.

DateFormatter

OK, so now that we know how to create Dates we need to figure out how to display them. That’s where the DateFormatter class comes in.

So What’s a DateFormatter?

DateFormatter provides a bunch of convenient ways to convert from Dates to Strings and back using all sorts of different formats. Let’s check out a few examples using our rightNow date from earlier.

In order to work with DateFormatter you need to create a new instance then tell it which format to use for converting a Date to String. The code above shows a few different formats you can use, but there are a ton of ways you can display dates. I highly recommend you check out this resource for formatting dates as strings when you start working with them yourself: https://nsdateformatter.com/

Sign up for our newsletter and stay up to with blog posts, industry news, and more.