convert a date to a string in swift

To convert a Date object to a String object in Swift, you first need to create an instance of DateFormatter class.

main.swift
let dateFormatter = DateFormatter()
36 chars
2 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.swift
dateFormatter.dateFormat = "dd-MM-yyyy"
40 chars
2 lines

Alternatively, if you want to display the date using the device's default format, you can use the following:

main.swift
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
66 chars
3 lines

Once the formatter is set up, you can use it to convert the date to a string:

main.swift
let date = Date()
let dateString = dateFormatter.string(from: date)
68 chars
3 lines

In this case, dateString will contain the string representation of the current date, based on the format set up in dateFormatter.

gistlibby LogSnag