iPhone - how to get user's date format

2019-05-21 10:42发布

问题:

How can I know what date format user prefers? Is there a way to read it from phone's local settings? Does the user prefer to read date in format "dd/mm/yyyy" or "mm/dd/yyyy"?

Thank you in advance.

回答1:

Use NSDateFormatter, but set the style (not the format) so it uses the user's locale formats.

e.g. create an NSDateFormatter and configure it thusly

[dateFormatter setDateStyle:NSDateFormatterShortStyle];

(for mm/dd/yy type dates, which are dd/mm/yy in other countries)



回答2:

CFDateFormatter defines several date and time format styles—short, medium, long, and full. It also defines a "none" style that you can use to suppress output of a component. The use of styles is illustrated in “Using Date Format Styles.” The date and time styles do not specify an exact format—they depend on the locale, the user preference settings, and the operating system version. If you want an exact format, use the CFDateFormatterSetFormat function to change the format strings, as shown in “Using Date Format Strings.”

CFDateFormatter

Should do the trick.



回答3:

Do you really want to know the exact format, or just convert between NSDate and NSString objects according to it? If the latter, then NSDateFormatter is your man, automatically producing the right format for the user's preferences.



回答4:

To know which format user prefer: i used [[dateFormatter locale] localeIdentifier] . If it returns en_US it means date is in mm/dd/yyyy format otherwise dd/mm/yyyy format. dateFormatter is an instance of NSDateFormatter class.



回答5:

Just in case you want the locale settings before formatting a date, you need to use NSLocale, like so:

NSLocale *locale = [NSLocale currentLocale];

This contains a slew of information about the current locale settings - read the docs for detailed info.



回答6:

Vishwa, the US isn't the only country to use the "mm/dd/yyy" format, and "dd/mm/yyyy" isn't the only alternative.

See http://en.wikipedia.org/wiki/Calendar_date#List_of_the_world_locations_by_date_format_in_use for more info.



回答7:

Since iOS 6 you can use "localizedStringFromDate"

NSString*localizedDate = [NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterShortStyle];