Working with Dates in Swift

Dates.png

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!

let rightNow = Date()

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.

let rightNow = Date()
let tomorrow = Date(timeIntervalSinceNow: 86400)
let aFewDaysLater = Date(timeInterval: (86400 * 3), since: rightNow)

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.

let rightNow = Date()
let formatter = DateFormatter()

formatter.dateFormat = "MM/dd/yyyy HH:mm"
print(formatter.string(from: rightNow)) // "02/28/2020 07:30"

formatter.dateFormat = "EEEE, MMM d, yyyy"
print(formatter.string(from: rightNow)) // "Friday, Feb 28, 2020"

formatter.dateFormat = "MM-dd-yy"
print(formatter.string(from: rightNow)) // "02-28-20"

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/

Previous
Previous

Responding to Keyboard Presentation/Dismissal in Swift

Next
Next

How to Add Borders to Views in SwiftUI