Clicky

iOS Dev Nugget 206 Date doesRelativeDateFormatting

.

Need to run a code review on your codebase? Hire me

In NSDate (now Date), there's a handy property doesRelativeDateFormatting that, when enabled, returns string values such as "today" and "tomorrow" from string(from:) when appropriate in that locale:

let dateFormatter1 = DateFormatter()
dateFormatter1.dateStyle = .full
dateFormatter1.doesRelativeDateFormatting = true
print(dateFormatter1.string(from: d)) //Today

let dateFormatter2 = DateFormatter()
dateFormatter2.dateStyle = .full
print(dateFormatter2.string(from: d)) //Thurs, September 22, 2016

let dateFormatter3 = DateFormatter()
dateFormatter3.dateStyle = .full
dateFormatter3.locale = Locale(identifier: "zh_Hans_SG")
dateFormatter3.doesRelativeDateFormatting = true
print(dateFormatter3.string(from: d)) //Chinese equivalent of "Today"


Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues