
Creating valid dates using the Swift language
Learn how to convert DateComponents into a valid Date using a Calendar instance.
Date
is the type we use to handle calendar information in Swift. It stores all the information needed to represent a specific point in time, independent of any calendar or time zone, by representing a time interval relative to an absolute reference date.
var birthday: Date = Date.now()
In an application’s user interface, it is common to handle dates and times by picking specific calendar values to represent the date. A user will usually choose a day, a month, an hour, or a minute, for example and then your application will have to transform that value into a valid Date
value.
That’s where DateComponents
comes in handy. It allows you to represent a date or time in terms of units, which can then be evaluated in a calendar system and time zone.
var components = DateComponents()
components.year = 2025
components.month = 6
components.day = 9
components.hour = 10
components.minute = 00
To evaluate a DateComponent
value in a calendar system and time zone use the Calendar
type and the type method date(from:)
.
let calendar = Calendar.current
if let date = calendar.date(from: components) {
print("Valid date: \(date)")
} else {
print("Invalid date")
}
It can also be done the other way around. DateComponents
has a calendar
property. By assigning a calendar value to it, you can access the date property to obtain a validated date calculated using the current components and the assigned calendar.
var components = DateComponents()
components.year = 2025
components.month = 6
components.day = 16
components.calendar = Calendar(identifier: .gregorian)
if let date = components.date {
print("The date is valid!")
} else {
print("The date is not valid...")
}