UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

return date with 3 different styles

Forums > Swift

is this code the best way to output this "2019/2/14 | 2019-2-14 | 2/14/2019" from input "2019/2/14"

func date_format2(date: String ) -> String {
  // write your code here
    let inputFormatter = DateFormatter()
       inputFormatter.dateFormat = "YYYY/m/d"
       let showDate = inputFormatter.date(from: date)
       let outputFormatter1 = DateFormatter()
        outputFormatter1.dateFormat = "YYYY/m/d" + " | " + "YYYY-m-d" + " | " + "m/d/YYYY"

       let resultString = outputFormatter1.string(from: showDate!)
        return resultString
}

3      

This is how I would do it:

func date_format2(date: String ) -> String {
    let fmt = DateFormatter()
    fmt.dateFormat = "YYYY/m/d"
    guard let inputDate = fmt.date(from: date) else {
        return date
    }

    fmt.dateFormat = "YYYY/m/d" + " | " + "YYYY-m-d" + " | " + "m/d/YYYY"
    return fmt.string(from: inputDate)
}

Two notes:

  • Reuses the DateFormatter object since those can be expensive to create. Just change the dateFormat property to the desired output format.
  • Uses a guard to return an empty string if the input date cannot be converted to a Date rather than using a force unwrap.

4      

Thank you, nice formatting.

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.