decode date in swift

In Swift, you can use the DateFormatter class to decode a string representation of a date and convert it into a Date object.

Here's an example of how to use DateFormatter to decode a date string:

main.swift
let dateString = "2022-01-01"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
if let date = dateFormatter.date(from: dateString) {
    print(date)
}
177 chars
7 lines

In this example, we first create a string representation of a date (dateString). We then create a DateFormatter object and set its dateFormat property to match the format of the date string ("yyyy-MM-dd"). Finally, we use the date(from:) method of the DateFormatter class to convert the date string into a Date object.

Note that the date(from:) method returns an optional Date object, so we use optional binding to safely unwrap the result and print it to the console.

This code should output the following:

main.swift
2022-01-01 00:00:00 +0000
26 chars
2 lines

which is the Date object representation of the original date string.

gistlibby LogSnag