Reputation: 661
I'm trying to display the month and day of a given date, like so:
"November 5"
but allow it to change the order based on locale.
"5 November" (or whatever other people do)
I am aware that I can simply hard code the formats like so:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM d"];
But, this doesn't update for locale, and I don't want to have to hard code a list of locales that use one style or the other.
Generally when I want to display a date for a given local, I know that I can use setDateType on the formatter, and pick from a number of pre-existing formats that will nicely account for the current locale. Unfortunately, none of the existing NSDateFormatterStyle will display the way I need them to.
The one solution I have been able to think of is to set the date style to long style, and then read through the dateFormat string, and see if I hit a 'd' or 'M' first. Then format it accordingly. This would be fairly easy to do, but it seems really hacky. Surely there is a better way to do that.
Any suggestions?
Upvotes: 1
Views: 75
Reputation: 661
Apparently NSDateFormatter dateFormatFromTemplate is a thing, and it solves my problem.
NSString *format = [NSDateFormatter dateFormatFromTemplate:@"MMMM d" options:0 locale:[NSLocale currentLocale]];
This will format the date correctly following your template according to current locale.
Upvotes: 1