Scott Kilbourn
Scott Kilbourn

Reputation: 1586

Get Locale Date Format Information

Using Swift 4, is there a way to get a string representation of a locale's date format? Based on an iPhone's locale settings, I would like to find out if the format is yyyy/mm/dd or mm/dd/yyyy.

I've found all of the ways for changing a date format or getting the date from the locale's format but have not been able to work out how to get the actual format.

Upvotes: 11

Views: 5749

Answers (1)

rmaddy
rmaddy

Reputation: 318794

Use DateFormatter dateFormat(fromTemplate:options:locale:).

let userFormat = DateFormatter.dateFormat(fromTemplate: "yyyyMMdd", options: 0, locale: Locale.current)

In the US this returns MM/dd/yyyy. In Germany this gives dd.MM.yyyy.

If you ever need to get the appropriate time format which also takes into account the user's chosen 12/24-hour time format, use a template of jms. The j is a special format specifier, only used with templates, that returns either h or H for the hour depending on what's appropriate.


Another possible option is to create a DateFormatter, set the desired dateStyle and timeStyle, then read the dateFormat property:

var mydf = DateFormatter()
mydf.dateStyle = .long // set as desired
mydf.timeStyle = .full // set as desired
print(mydf.dateFormat)

For the US this gives:

MMMM d, y 'at' h:mm:ss a zzzz

For Germany this gives:

d. MMMM y 'um' HH:mm:ss zzzz

Upvotes: 18

Related Questions