An easy way to convert dates to strings in Swift 4

Swift is a brilliant language. It’s relatively easy to learn and incredibly intuitive. There are a few things that aren’t that straightforward though. For example if you want to convert a number into a string there are many ways.

String(number)
"\(numb)"

But that doesn’t work for dates. You get the current date by calling Date() but what if you want to populate a core data object that requires a string – but you still want to show a date? What if you want to put the date in a readable format? You need to use a date formatter, convert it then output a string.

I was doing this over and over until I decided to create a very simple function to do it for me. So I can find it again I’m posting it here – but that means anyone who stumbles on the page while searching for a solution could also use it.

    func formatDate(_ dateString:Date) -> String {
        let dateIn = dateString
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .medium
        dateFormatter.timeStyle = .short
        
        dateFormatter.locale = Locale(identifier: "en_GB")
        
        return dateFormatter.string(from:dateIn)
    }

Just put that function in the swift page you want and call it. You can use Date() in the parameters field to get the current date or pass in whatever date you already in the date format.

let dateString = formatDate(Date())

It will then output a string value that you can use. The method is written with the format coded in so if you want to change it to long, short or no time/date you just change dateStyle and timeStyle elements in the function.

You could even pass these in the parameters to set them in each circumstance if you need multiple date conversions.

    func formatDate(_ dateString:Date, dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style) -> String {
        let dateIn = dateString
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = dateStyle
        dateFormatter.timeStyle = timeStyle
        
        dateFormatter.locale = Locale(identifier: "en_GB")
        
        return dateFormatter.string(from:dateIn)
    }

You’d then just call the same DateFormatter but with the extra parameters as discussed. That will then display the date in the format you outlined.

let dateString = formatDate(Date(), dateStyle: .medium, timeStyle: .short)

Leave a Reply