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.swift236 chars11 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.
gistlibby LogSnag