Tuesday, May 18, 2021

Parsing Dates Without Times

Quinn the Eskimo:

Parsing fixed-format date strings is tricky. For an explanation as to why, see QA1480 NSDateFormatter and Internet Dates. However, there’s an extra gotcha when you try to parse fixed-format date strings that don’t include a time.

[…]

This is failing because, internally, the date formatter maps the date string to a set of date components (DateComponents). The year, month, and day come from the date string, but the hour, minute, and second default to 0. In Brazil, daylight saving time starts at midnight, and thus the date components year: 2018, month: 11, day: 4, hour: 0, minute: 0, second: 0 don’t exist in the São Paulo time zone. When the date formatter runs these components through the calendar, it returns nil.

[…]

The solution here is to set the defaultDate property on the date formatter to something in the middle of the day.

It’s not documented exactly what this does, but I presume that missing date components get taken from the defaultDate. This still makes me a bit nervous, though, because what if I have an unlucky default date whose time produces a date that doesn’t exist in that time zone? Apparently, the isLenient property can help with that.

See also: The Wisdom of Quinn.

Previously:

Comments RSS · Twitter

Leave a Comment