Determining Whether a Date Is Within a Given Range
06 December, 2020
Before beginning this tutorial, create a new playground file in Xcode to follow along within.
Select File → New → Playground... then select the macOS tab and a Blank playground type. Press the Next button and then save your playground in an appropriate location on your computer.
Don't worry if you intend to use this logic in an iOS project or in a project on another Apple platform.
The required classes are part of the Foundation
framework and are available on all Apple platforms.
Get the date as a Date
Say that you are starting with a date and time encoded within a string.
To do any work with dates and times, you want to get that value converted into an actual instance of the Date
type as soon as possible.
To do so, run the following code:
// December 6, 2020 at 5:00 PM
let dateTimeAsString = "2020-12-06 17:00"
// Create an instance of DateFormatter
let formatter = DateFormatter()
// Tell the formatter how to read the string
formatter.dateFormat = "YYYY-MM-DD HH:mm"
// Create an instance of the Date type using the information from the string
let dateTime = formatter.date(from: dateTimeAsString) ?? Date()
Note the use of the nil coalescing operator on the final line of code. This ensures that if the String
cannot be successfully converted into a Date
, a default value of the current date and time is used instead. Given how easy it is for a date value to be incorrectly specified it is not recommended to force-unwrap the value returned by the date(from:)
method.
Once you have a date-time value as an actual instance of the Date
type you are halfway to a solution.
Now, say that you want to determine if a certain date-time value is within an hour after the date-time value you just found.
This is where Swift's notion of a range is very useful.
Add the following code to your playground:
// Create a constant for one hour ahead
// NOTE: Time intervals are specified in seconds.
// So, 60 seconds by 60 minutes is 1 hour.
let anHourAhead = dateTime.addingTimeInterval(60 * 60)
// Define the range of times
let range = dateTime...anHourAhead
// Create a constant that is within the range of an hour
let withinRange = dateTime.addingTimeInterval(60 * Double.random(in: 0...59))
// Create a constant that is past the range of an hour
let pastRange = dateTime.addingTimeInterval(60 * Double.random(in: 61...120))
// Returns true
range.contains(withinRange)
// Returns false
range.contains(pastRange)
The final two lines of code produce a boolean value – true or false.
You can use that type of logic within a conditional statement to take whatever action you wish within your application.