To convert a Date
object to a String
object in Swift, you first need to create an instance of DateFormatter
class.
main.swift36 chars2 lines
For displaying a user-friendly string, you may want to set a format that can be easily read by humans. For example, to obtain a date in the format dd-MM-yyyy
you would do:
main.swift40 chars2 lines
Alternatively, if you want to display the date using the device's default format, you can use the following:
main.swift66 chars3 lines
Once the formatter is set up, you can use it to convert the date to a string:
main.swift68 chars3 lines
In this case, dateString
will contain the string representation of the current date, based on the format set up in dateFormatter
.
gistlibby LogSnag