Search code examples
swiftdatensdateformatter

Swift - Convert a short format string of a date to long format using date formatter


I have a string that looks like this: "2021-08-05"

I would like to convert it into a date so that I can display it as "5th August 2021"

My code below just returns as nil and I don't understand why. Any help would be appreciated.

Code:


func stringToDate(dateString: String){
  let formatter = DateFormatter()

  formatter.locale = Locale(identifier: "en_US_POSIX")
  formatter.dateFormat = "yyyy-MM-dd"
  formatter.dateStyle = .long
        
  let newDate = formatter.date(from: dateString)

  print("formatter: \(newDate)")
}

I call the function as an action for a button (SwiftUI), so when the button is clicked the date should show.

Button("Go"){
 stringToDate(dateString: "2021-08-05")
}


Solution

  • Removing the dateStyle line fixes it, and an actual date is printed.

    Code:

    func stringToDate(dateString: String){
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "yyyy-MM-dd"
    
        let newDate = formatter.date(from: dateString)
        print("formatter: \(newDate)")
    }
    
    // Prints: formatter: Optional(2021-08-04 23:00:00 +0000)
    

    To do the whole conversion, the following function will work:

    func convertDate(from original: String) -> String? {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "yyyy-MM-dd"
        guard let date = formatter.date(from: original) else { return nil }
        formatter.dateStyle = .long
        let string = formatter.string(from: date)
        return string
    }
    
    // Prints: Optional("August 5, 2021")
    

    Of course, this may be printed slightly different due to my location & language

    The following line of code can only be run after getting a Date otherwise you are 'overwriting' the dateFormat:

    formatter.dateStyle = .long