Date and time format after setting the current area of ​​the device

I have an NSDate object from which I am making two NSStrings: date and time. I am currently formatting the date as 20111031 and the time as 23:15.

What I would like to do is format it to the current region settings (iPhone, iPad, iPod Touch) (and not in the language!). For example:

  • A device installed in the US region will show (from the top of the head) 10.31.11 and the time is 11:15 pm
  • A device installed in the Netherlands region will show: 31-10-2011 and time 23.15
  • A device installed in the Swedish region will show: 2001-10-31 and the time 23:15

How can i do this?

+7
source share
2 answers

Enough of the following: NSDateFormatter by default has a default standard for the phone:

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

FYI here, what happens to the USA, the 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 
+37
source

There are many great snippets of code here. Even better in my opinion on international date formats (when all I want is a date, not time), since the phone knows the locale language in the settings:

 NSDate *date = [NSDate date]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:NSLocaleIdentifier]]; [dateFormatter setTimeStyle:NO]; [dateFormatter setDateStyle:NSDateFormatterShortStyle]; NSLog(@"%@",[dateFormatter stringFromDate:date]); 
+7
source

All Articles