简体   繁体   中英

Date from String using DateFormatter returning nil

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

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM