Date
object to a nicely formatted string such as “10 days ago” or “next month” required a lot of custom coding or maybe third-party libraries to manage the conversion. DateFormatter
is very versatile, as well as necessary for easy date localizations, but just can’t make a nicely formatted relative date across all date ranges. The DateFormatter.doesRelativeDateFormatting
property (available since iOS 4) will output some simple relative date strings like “today” and “tomorrow” but can’t handle relative seconds, minutes, hours, etc. and complex cases. RelativeDateTimeFormatter
class!RelativeDateTimeFormatter
and got much more interesting and useful results! string
method switched from from:
to for:
with the new class. Also note that forward-looking relative time strings seem to currently be off by 1 second (as of iOS 13.3.1); if you want an accurate forward-looking time string (e.g. ‘in 1 minute’ instead of ‘in 59 seconds’), you’ll need to be aware of that and compensate potentially.dateTimeStyle
of .numeric
to make that happen.unitStyle
property, you can also control whether the words are full-length or abbreviated, as well as whether numbers are numeric or spelled out completely.RelativeDateTimeFormatter
(and why you should almost always use system formatters for user-facing numbers, dates, etc.) is that we can easily get locale-specific versions of these relative dates and times with just one more line of code using the locale
property.RelativeDateTimeFormatter
documentation, but at present, like a fair amount of the iOS 13 documentation, there are no overviews, descriptive text, etc. You’ll be better off using the code comments from the ‘Jump to Definition…’ context menu option in Xcode 11.MeasurementFormatter
, ListFormatter
, and other classes for generating localized, user-friendly strings for all of your data.