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.swift164 chars5 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