Skip to content

Instantly share code, notes, and snippets.

@Me1000
Created August 24, 2012 03:09
Show Gist options
  • Save Me1000/3445058 to your computer and use it in GitHub Desktop.
Save Me1000/3445058 to your computer and use it in GitHub Desktop.
/**
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];
@Me1000
Copy link
Author

Me1000 commented Aug 24, 2012

@dbrajkovic
Copy link

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:@"."];
}

@Me1000
Copy link
Author

Me1000 commented Aug 24, 2012

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.

@dbrajkovic
Copy link

Sounds like a job for NSRegularExpression

@RomainBoulay
Copy link

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