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.swift177 chars7 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.swift26 chars2 lines
which is the Date
object representation of the original date string.
gistlibby LogSnag