Search code examples
iosswiftdatensdateformatter

How to format a Date to a specific format on Swift4?


I must format a object created by Date() to a especific format, this format must show the date like:

28 may, 2018 11:00:32

I've a func to make the formatation of Date(), but to the follow format:

yyyy-MM-dd HH:mm:ss

Function working:

static func dateFormatTime(date : Date) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        return dateFormatter.string(from: date)
    }

But I don't know how make on this format: dd MMM, yyyy HH:mm:ss


Solution

  • Simply, all you have to do is to change the dateFormatter.dateFormat value to the desired format, which is "dd MMM, yyyy hh:mm:ss" in your case:

    func dateFormatTime(date : Date) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd MMM, yyyy hh:mm:ss"
        return dateFormatter.string(from: date)
    }
    

    therefore:

    let str = dateFormatTime(date: Date())
    print(str) // 29 May, 2018 12:18:08
    

    Time zone:

    You could also set the desired time zone like this:

    dateFormatter.timeZone = TimeZone(identifier: "UTC")
    

    Update:

    Thanks for @rmaddy for suggesting using date styles (dateStyle and timeStyle properties) instead of editing the date format.

    When displaying a date to a user, you set the dateStyle and timeStyle properties of the date formatter according to your particular needs... Based on the values of the dateStyle and timeStyle properties, DateFormatter provides a representation of a specified date that is appropriate for a given locale.

    DateFormatter - Working With User-Visible Representations of Dates and Times.

    Hence:

    func dateFormatTime(date : Date) -> String {
        let dateFormatter = DateFormatter()
        
        dateFormatter.dateStyle = .long
        dateFormatter.timeStyle = .medium
        
        dateFormatter.timeZone = TimeZone(identifier: "UTC")
     
        return dateFormatter.string(from: date)
    }
    
    let str = dateFormatTime(date: Date())
    print(str) // May 29, 2018 at 12:45:08 AM