iPhone - how to get user's date format

2019-05-21 10:20发布

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.

7条回答
来,给爷笑一个
2楼-- · 2019-05-21 10:55

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)

查看更多
ら.Afraid
3楼-- · 2019-05-21 10:59

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.

查看更多
看我几分像从前
4楼-- · 2019-05-21 11:09

Since iOS 6 you can use "localizedStringFromDate"

NSString*localizedDate = [NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterShortStyle];
查看更多
啃猪蹄的小仙女
5楼-- · 2019-05-21 11:13

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楼-- · 2019-05-21 11:15

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.

查看更多
Deceive 欺骗
7楼-- · 2019-05-21 11:16

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.

查看更多
登录 后发表回答