Created
August 24, 2012 03:09
-
-
Save Me1000/3445058 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Goal: have a properly localized date (month/day in the correct order), yet | |
have a custom date component separator. | |
Example as follows: | |
*/ | |
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; | |
NSLocale *gbLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"]; | |
NSLocale *deLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"de_DE"]; | |
NSLocale *frLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"]; | |
NSString *localDateString = [NSDateFormatter dateFormatFromTemplate:@"MdY" options:0 locale:gbLocale]; | |
NSString *localDateString2 = [NSDateFormatter dateFormatFromTemplate:@"MdY" options:0 locale:usLocale]; | |
NSString *localDateString3 = [NSDateFormatter dateFormatFromTemplate:@"MdY" options:0 locale:frLocale]; | |
NSString *localDateString4 = [NSDateFormatter dateFormatFromTemplate:@"MdY" options:0 locale:deLocale]; | |
NSLog(@" GB:%@ \n US:%@ \n FR:%@ \n DE:%@", localDateString, localDateString2, localDateString3, localDateString4); | |
/* | |
Output: | |
GB:d/M/Y | |
US:M/d/Y | |
FR:d/M/YYYY | |
DE:d.M.Y | |
*/ | |
// What's the right way to do this: | |
// because this is gross… | |
localDateString = [localDateString stringByReplacingOccurrencesOfString:@"/" withString:@"."]; | |
// such that the formatter string will ALWAYS use a dot instead of a slash or dash? | |
[formatter setDateFormat:localDateString]; |
How about adding a category to NSDateFormatter
+ (NSString *)dateFormatFromTemplate:(NSString *)template options:(NSUInteger)opts locale:(NSLocale *)locale separator:(NSString*)separator
{
NSString *format = [NSDateFormatter dateFormatFromTemplate:template options:opts locale:locale];
return [format stringByReplacingOccurrencesOfString:@"/" withString:@"."];
}
Sure, you could do that… the issue is that "/" might not be the only separator.
The way to do this such that we account for all possible values is to just strip all characters that aren't in the set {M, d, Y}.
Then add the dot after the first and second characters.
Sounds like a job for NSRegularExpression
Hey @Me1000,
Did you solve this? I would be curious to know if there's a better solution?
Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Answer thus far: https://twitter.com/davedelong/statuses/238842053486858240
No built in way…