Search code examples
swiftnsdateformatter

Date function returning incorrect result


I cannot find an equivalent answer that resolves for me eg

Please see the code. I'm formatting an incoming string (item[9]) downloaded from a webservice.

var cal_end_date: Date!

var dateFormatter = DateFormatter()

let tempEndDate = item[9]

print("item[9]", item[9]) // 20190331
print("tempEndDate", tempEndDate) //20190331

dateFormatter.dateFormat = "YYYYMMDD"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone.autoupdatingCurrent

cal_end_date = dateFormatter.date(from:tempEndDate)!
print(#function, "cal_end_date:", cal_end_date!) //2019-01-31 05:00:00 +0000    

The end date has the wrong month! I have confirmed this result by running the code in a playground with a fixed date. Am I doing something wrong here? Has something changed in Swift 5? Thanks


Solution

  • You can always use nsdateformatter.com to check if your dateFormat for your formatter is correct (next to the Examples check Reference which shows you what each letter/letters represent).

    In your case, you have to be carefull on dateFormat's case sensitive. Days and years are represented by small letters

    dateFormatter.dateFormat = "yyyyMMdd"