1

I need the date as a string but not the time and it has to be localized.

So for example USA should be Sep 25 2009 but for New Zealand it would be 25 Sep 2009. I can get the date into a string by specifying the format "MMM dd YYYY" but It's not localized.

Any ideas?

McKay
  • 11
  • 2

2 Answers2

7
[NSDateFormatter localizedStringFromDate:[NSDate date]
                               dateStyle:NSDateFormatterMediumStyle
                               timeStyle:0]
Sophie Alpert
  • 139,698
  • 36
  • 220
  • 238
RJ.
  • 289
  • 1
  • 2
  • is this available on the iPhone? doesn't appear to be in the iPhone-specific NSDateFormatter docs. – David Maymudes Nov 30 '09 at 17:42
  • 2
    timeStyle should be set to kCFDateFormatterNoStyle. It happens to be 0 but you really shouldn't hardcode constants when there is a named constant provided. – progrmr Dec 18 '09 at 19:08
3

The key is to send setTimeStyle:kCFDateFormatterNoStyle to the dateFormatter. That sets the dateFormatter so that it will only format the date and not output the time:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];    
[dateFormatter setLocale: [NSLocale currentLocale]];    
[dateFormatter setDateStyle:kCFDateFormatterShortStyle]; // or whichever style...
[dateFormatter setTimeStyle:kCFDateFormatterNoStyle];   
NSString* dateString = [dateFormatter stringFromDate: [NSDate date]];

This gives me the following output:

12/18/09
progrmr
  • 75,956
  • 16
  • 112
  • 147
  • May i get time without date in the same manner? if yes then it is not working for me. When i get time in NSDate then my object remains nil – Mashhadi Oct 04 '12 at 06:20
  • It should work. Post your code with a new question if you can't get it working. – progrmr Oct 04 '12 at 19:15
  • http://stackoverflow.com/questions/12721553/get-time-from-nsdate-returns-nil/12721934#12721934 – Mashhadi Oct 08 '12 at 11:08