Daniel Wood Daniel Wood - 18 days ago 10
iOS Question

DateFormatter producing unexpected result on device

I have the following code:

var components = DateComponents()
components.year = 2017
components.month = 1

var calendar = Calendar.current
let date = calendar.date(from: components)!

let formatter = DateFormatter()
formatter.setLocalizedDateFormatFromTemplate("MMMMYYYY")
let string = formatter.string(from: date)


When I run this in the simulator on my computer it works as I would expect and the value of
string
is January 2017.

However, when I run the same code on my device the value of
string
is January 2016. What can be causing this difference?

Answer

The difference could be

  • A different locale on device and simulator.

and / or

  • YYYY is year in a Week of Year based calendar.
  • yyyy is year in standard calendar.

You should always use yyyy.

Comments