Date Formatters, Calendars, and Locales

Today I tweeted:

Something I’ve long wondered: Why does NSDateFormatter have a locale property, when it could use the one supplied by calendar?

Let me try and explain a bit. An NSDateFormatter instance has properties for both its locale and its calendar. The calendar in turn has its own locale property. Here’s a quick diagram to demonstrate:

IMG 2211

please excuse:
A) that I sketched this on the whiteboard because I’m too lazy to draw it on the computer
B) NSTimeZone. We’ll get to that in a moment


That whole graph of objects starts to feel a bit dangerous to me — am I setting the right locale in the right place? Hope so!

Happily the world replied to my quest, including this particularly helpful playground screenshot from Daniel Tomlinson:

This shows that setting the formatter’s locale passes that onto the calendar too, which suggests that maybe NSDateFormatter.locale is just a convenience.

But if you try setting the calendar’s locale directly, that leaves the formatter’s locale property alone. So the formatter does have its own direct locale reference (as in my diagram above). This potentially leaves you with a formatter and calendar that reference very different locales. Would that cause nasty things to happen? Who knows!

The NSDateFormatter docs should probably tell you something along these lines:

Locale is used to properly format date strings in a locale-specific manner. Setting a formatter's locale passes that along to the receiver’s calendar too. Please avoid setting the calendar’s locale directly.

But they don’t. Instead all you get told is the utterly pointless: “The locale for the receiver.”

There also seems to be some special behaviour that kicks in if you set the formatter’s calendar, and that calendar happens to come with a different locale to the one the formatter is already using. But as this point I’m too tired to investigate that one.


And what of the time zone? You’ll notice in the diagram that it follows a very similar pattern to the locale. Both formatter and calendar have a public property pointing at an NSTimeZone instance. Seems logical to expect then the behaviour is the same as for locales.

But no. In my quick test, formatter and calendar references to timezone are completely independent. Setting one does not affect the other.

© Mike Abdullah 2007-2015