Comparing dates with Foundation
This recipe will focus on one area of Foundation that is very widely used, that is, date and time manipulation and formatting.
We will create a function that determines how long there is until Halloween and return this information as a string that can be displayed to a user.
Getting ready
Create a new iOS playground and import the Foundation framework at the top of the playground:
import Foundation
How to do it…
Let’s create a function that will return a string telling us how long there is until Halloween. We can then print the result:
- Define the function:
func howLongUntilHalloween() -> String {
}
- Within the function, get the current calendar and time zone:
let calendar = Calendar.current
let timeZone = TimeZone.current
- Get the current date and time and use the calendar to get the current year:
let now = Date()
let yearOfNextHalloween = calendar.component(.year, from: now)
- Define date components that...