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

2019-06-09 04:57发布

问题:

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];