convert a string to a date in swift

To convert a string to a date in Swift, you first need to create an instance of the DateFormatter class, which allows you to specify the format of the date string. Once you have the formatter set up, you can call its date(from:) method to convert the string to a Date object.

Here's a code snippet that demonstrates how to do this:

main.swift
let dateString = "2021-04-30T15:30:00Z"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = formatter.date(from: dateString)
164 chars
5 lines

In this example, we have a string that represents a date in ISO 8601 format. We create a DateFormatter object and specify the format using the dateFormat property. Then we call the date(from:) method with the input string to get a Date object.

Note that formatting date strings can be tricky, so make sure to consult the Unicode Technical Standard #35 to ensure you're using the correct format for your needs.

gistlibby LogSnag