Daniel Wood Daniel Wood - 1 year ago 63
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()
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
is January 2017.

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download