Format date and time after device current region settings

16,395

Solution 1

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

Solution 2

Many great code snippets here. One even better in my mind for international date formats (when all I want is the date, not the time) is this as the phone knows the locale language in 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]);
Share:
16,395
Paul Peelen
Author by

Paul Peelen

Happy guy coding in swift for ios, tvos, macos and vapor amongst others.

Updated on June 13, 2022

Comments

  • Paul Peelen
    Paul Peelen almost 2 years

    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?

  • Paul Peelen
    Paul Peelen over 12 years
    Many thanks. Didn't know that. (feel kinda stupid now though) ;)
  • yuji
    yuji over 12 years
    My pleasure! I only know this because I spent the past three days dealing with NSDate-related bugs and learning way more about this stuff than I ever hoped :P