1

I've a String like yyyy-MM-dd and I want create a Date with this.

static func dateFromStringWithBarra(date : String) -> String {
    print("DATE: \(date)")
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    let date_from_format = dateFormatter.date(from: date)
    print("date_from_format: \(date_from_format)")
    dateFormatter.dateFormat = "dd/MM/yyyy"
    print("date_from_format: \(date_from_format)")
    return dateFormatter.string(from: date_from_format!) // <- nil
}

OUTPUT:

DATE: 2018-11-04 date_from_format: nil date_from_format: nil

Augusto
  • 3,825
  • 9
  • 45
  • 93

2 Answers2

0

I had the same problem, mine was solved by some reason just by adding the locale to the DateFormatter:

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "es_MX_POSIX")

Hope it helps.

-1

A few things about that code:

1) Not sure why you use two different date formats 2) You should avoid if possible to use force unwrapping, in this case probably guard would be a good choice.

Meaning that the code should look more like this:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

guard let date_from_format = dateFormatter.date(from: date) else {
    return ""
}
return dateFormatter.string(from: date_from_format)
Pablo
  • 97
  • 4
  • The point of two formats is to convert a date string to a new date string in a different format. Your code just returns the same string so there's no point to it. And your answer doesn't explain the issue. – rmaddy Oct 08 '18 at 17:20