I'm having trouble understanding the behaviour of the following code:
let enDateFormatter: DateFormatter = {
let df = DateFormatter()
df.dateFormat = "YYYY-MM-dd"
df.locale = Locale(identifier: "en")
return df
}()
let nlDateFormatter: DateFormatter = {
let df = DateFormatter()
df.dateFormat = "YYYY-MM-dd"
df.locale = Locale(identifier: "nl")
return df
}()
let date1 = enDateFormatter.date(from: "2017-01-01")!
enDateFormatter.string(from: date1)
nlDateFormatter.string(from: date1)
let date2 = nlDateFormatter.date(from: "2017-01-01")!
enDateFormatter.string(from: date2)
nlDateFormatter.string(from: date2)
This produces the following the result in playground:
For some reason nlDateFormatter
always returns 2016-01-01. Obviously this is off by a year and I'm trying to understand why it happens and how I can correct this. For reference I'm using xcode 8.
EDIT Found the issue
The problem was with using 'YYYY' as opposed to 'yyyy', where the first refers to ISO8601 year and the second to Gregorian year. Given that the 1st of January 2017 comes in to week 52 of 2016 this is translated to ISO year 2016. This is not the case with the gregorian year, which corresponds to the actual year as specified in the date object.