Search code examples
iosswiftdatedateformatter

Swift - Convert string to date


On iOS 11+ only, I have this bug : When user has disabled 24h mode in phone hour settings, my string can't be parse to date using this code.

On other iOS version, there is no problems...

Is something missing to force 24h mode for the formatter ?

Variables date and beginHour came from webservice.

// input date = 20171201
// input beginHour = 2359

let dateTimeFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "fr_FR")
dateFormatter.timeZone = TimeZone.autoupdatingCurrent
dateTimeFormatter.dateFormat = "yyyyMMdd HHmm"

if let date = dateTimeFormatter.date(from: date+" "+beginHour) {
    // ...
}

Solution

  • I think in your code, you are not using the right dateFormatter, kindly check between dateTimeFormatter and dateFormatter,

    let dateTimeFormatter = DateFormatter()
    dateTimeFormatter.locale = Locale(identifier: "fr_FR")
    dateTimeFormatter.timeZone = TimeZone.autoupdatingCurrent
    dateTimeFormatter.dateFormat = "yyyyMMdd HHmm"
    
    if let date = dateTimeFormatter.date(from: date+" "+beginHour) {
        // ...
    }