Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 760
Scott Kilbourn Avatar asked Jan 13 '19 00:01

Scott Kilbourn


People also ask

How do I get a locale date?

Use the toLocaleString() method to get a date and time in the user's locale format, e.g. date. toLocaleString() . The toLocaleString method returns a string representing the given date according to language-specific conventions.

What is locale date?

The LOCALE functions take an alphanumeric item (a character string) in the format of a date, for the LOCALE-DATE intrinsic function, or in the format of a time, for the LOCALE-TIME intrinsic function and return another alphanumeric item with the date or time formatted in a culturally appropriate way.

What is locale date string?

The toLocaleDateString() method returns a string with a language-sensitive representation of the date portion of the specified date in the user agent's timezone. In implementations with Intl. DateTimeFormat API support, this method simply calls Intl. DateTimeFormat .


1 Answers

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

like image 136
rmaddy Avatar answered Sep 19 '22 23:09

rmaddy