Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format date and time after device current region settings

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?

like image 870
Paul Peelen Avatar asked Oct 29 '11 21:10

Paul Peelen


People also ask

What is region format example on Iphone?

If you go onto General, then you go onto Language and Region, and you then scroll down it says Region Format Example, a time and a date. Under the date it says a specific amount of money, like £1234.56 - £4567.89.

How do I change the date format in Windows 10 for all users?

Navigate to the HKEY_USERS\Default User\Control Panel\International registry subkey. Double-click the sShortDate registry entry. Set the value to the date format required (e.g., dd/MM/yyyy), then click OK. You can also change the sLongDate registry entry for the longer date format (e.g., dd MMMM yyyy), then click OK.


1 Answers

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
like image 158
yuji Avatar answered Sep 30 '22 07:09

yuji