date from string ios 15 in swift

In Swift, you can convert a string to a date using DateFormatter. The following example demonstrates how to convert a string with the yyyy-MM-dd format to a Date object:

main.swift
let dateString = "2022-01-01"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: dateString)

if let date = date {
    print(date)
} else {
    print("Invalid date string")
}
236 chars
11 lines

In the code above, we first define a string with the date in the format yyyy-MM-dd. We then create a DateFormatter object and set its dateFormat property to match our date string. Finally, we use the date(from:) method of the formatter to convert the string to a Date object.

If the input string is not in the correct format, the date(from:) method will return nil, so it's important to check for this and handle the error appropriately.

related categories

gistlibby LogSnag