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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.