Get the user's date format? (DMY, MDY, YMD)

為{幸葍}努か 提交于 2019-12-08 13:37:10

问题


I'm creating a form where the user can enter their birthday with 3 UITextFields: 1 for month, 1 for day and 1 for year. I'd like to arrange them based on the user's date format.
i.e.: [ MONTH ] [ DAY ] [ YEAR ] for American users, [ DAY ] [ MONTH ] [ YEAR ] for European users, etc.
Map of the date format by country: http://en.wikipedia.org/wiki/Date_format_by_country#Map

What's the easiest way to get that format?

Right now I'm setting the date October, 20 2000 and parsing the string.

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:20];
[components setMonth:10];
[components setYear:2000];
NSDate *date = [calendar dateFromComponents:components];

NSLog(@"%@", [NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterNoStyle]);

But I don't think it's the right thing to do since I got already too many different formats:

US: 10/20/00
FR: 20/10/00
Japan: 2000/10/20
Sweden: 2000-10-20


回答1:


You can make use of NSDateFormatter dateFormatFromTemplate:options:locale:.

NSString *base = @"MM/dd/yyyy";
NSLocale *locale = [NSLocale currentLocale];
NSString *format = [NSDateFormatter dateFormatFromTemplate:base options:0 locale:locale];

The value of format will be adjusted with the right format based on the locale. The trick now is to scan format to see what order you find M, d, and y.




回答2:


You can try setting the dateStyle of dateFormatter.

NSDateFormatter  *dateFormatter = [[NSDateFormatter alloc]init];
//Based on users locale it would automatically change the display format
[dateFormatter setDateStyle:NSDateFormatterShortStyle];

NSString *dateString = [dateFormatter stringFromDate:date];


来源:https://stackoverflow.com/questions/16090993/get-the-users-date-format-dmy-mdy-ymd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!