Search code examples
objective-cdatetimelocalizationnsdate

Elegant implementation of relative date ranges in Objective-C


I want to display a date range for my users. I need something smart, but localization independent method for displaying only the necessary parts of the range end like this:

2017-jan-1 to 2017-feb-22017-jan-1 to feb-2

2017-jan-1 to 2017-jan-22017-jan-1 to 2

2017-jan-1 to 2018-jan-22017-jan-1 to 2018-jan-2

I could write several ifs to check if the components are the same, but then I had to write format strings by hand, which I don't want because other localizations need other month/day orders.

Is there a system API similar to doesRelativeDateFormatting or a CocoaPods library for this? How would you do it?


Solution

  • The NSDateFormatter method +dateFormatFromTemplate:options:locale: addresses the point at which you thought your approach failed. Given a template specifying the parts of a date you wish included; the example Apple uses being day name, day number and month; it returns an appropriate format string for the locale and user preferences.

    HTH