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

SOLVED: Swift 5: DateFormatter Convert String to Date with Extension

Forums > Swift

I want to convert a string to a date, and then return a string again. I did this extension, but when I use it it doesn't work as it should.

For example if I have "2020-12-10" the result should be "10 de Diciembre de 2020", however I always get the same result "22 de Diciembre de 2021" and its not correct.

This is my code:

extension String {
    func dateFormatter(style: DateFormatter.Style) -> String? {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        formatter.timeZone = .current
        formatter.dateStyle = style
        formatter.locale = Locale(identifier: "es_AR")
        return formatter.string(from: Date())
    }
}

let dateExample = "2022-09-08" // This should be "8 de Septiembre de 2022"

let dateFormat = dateExample.dateFormatter(style: .long) // here i get "22 de diciembre de 2021"

3      

Two things:

  1. You never tell your function to parse a date from the string, and
  2. You always return a string from the current date: return formatter.string(from: Date())

Try this instead:

extension String {
    func roundTripDate(style: DateFormatter.Style) -> String? {
        //set things up
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "es_AR")
        formatter.timeZone = .current

        formatter.dateFormat = "yyyy-MM-dd" // this is the date format coming in
        //this guards against a String not being in the correct format
        guard let date = formatter.date(from: self) else {
            return nil
        }

        formatter.dateStyle = style // this is the date format going out
        return formatter.string(from: date)
    }
}

let example1 = "2022-09-08"
print(example1.roundTripDate(style: .long))
//Optional("8 de septiembre de 2022")

//string is not a date
let example2 = "Hello world"
print(example2.roundTripDate(style: .long))
//nil

//string is a date but in the wrong input format
let example3 = "12/22/2021"
print(example3.roundTripDate(style: .long))
//nil

3      

Excellent!

  • Clear code example? CHECK!
  • Clear explanation? CHECK!
  • Code well documented? CHECK!
  • Exception test cases? CHECK!
  • Cool use of extentions? CHECK!

I copy / pasted this right into my 100 Days of SwiftUI Playground notebook for future reference. Nice!

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.