Format date and time after device current region settings

Paul Peelen picture Paul Peelen · Oct 29, 2011 · Viewed 16.3k times · Source

I have an NSDate object from which I make two NSStrings: The date and the time. Currently I format the date as 20111031 and time as 23:15.

What I would like to do is to format it to the device (iPhone, iPad, iPod Touch) current region settings (not the language!). So for instance:

  • A device set to region US would show (from the top of my head) 10.31.11 and time 11:15 pm
  • A device set to region the Netherlands would show: 31-10-2011 and time 23.15
  • A device set to region Swedish would show: 2001-10-31 and time 23:15

How can I do this?

Answer

yuji picture yuji · Oct 30, 2011

The following should be enough, because an NSDateFormatter has the phone's default locale by default:

NSDate *date = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSLog(@"%@",[dateFormatter stringFromDate:date]);

FYI here's what happens with US, Netherlands, and Sweden:

[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
NSLog(@"%@",[dateFormatter stringFromDate:date]);
// displays 10/30/11 7:09 PM 
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"nl_NL"]];
NSLog(@"%@",[dateFormatter stringFromDate:date]);
// displays 30-10-11 19:09
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"sv_SE"]];
NSLog(@"%@",[dateFormatter stringFromDate:date]);
// displays 2011-10-30 19:09