22

I am using dateformatter to get days and time in the my application. But I am facing an issue when I change the language of the phone dateformatter returns me day and time of the selected language of the phone due to which my app crashes as we are not supporting multiple languages.

Please find the below code snippet:

NSDate *date=[NSDate date];
NSDateFormatter *objTimeFotmatter=[[NSDateFormatter alloc]init];
[objTimeFotmatter setDateFormat:@"HH:mm"];

NSDateFormatter *objDayFotmatter=[[NSDateFormatter alloc]init];
[objDayFotmatter setDateFormat:@"EEEE"];

NSString *objTime=[objTimeFotmatter stringFromDate:date];
NSString *objDay=[objDayFotmatter stringFromDate:date];

NSLog(@"objTime=%@",objTime);
NSLog(@"objDay=%@",objDay);

When I selected the phone language as Gujrati (India) the output that I am seeing using the nslog using this is as follows,

2011-11-24 11:23:20.221 Belkin_Plugin[1110:707] objTime=૧૧:૨૩
2011-11-24 11:23:20.227 Belkin_Plugin[1110:707] objDay=ગુરુવાર
halfer
  • 19,824
  • 17
  • 99
  • 186
breakfreehg
  • 618
  • 1
  • 6
  • 16
  • might this be the same question [as this one](http://stackoverflow.com/questions/1348590/how-to-make-nsdateformatter-display-locale-specific-date) ??? – Michael Dautermann Nov 24 '11 at 06:26

3 Answers3

47

Add the following lines to the dateformatter.

NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:usLocale];

In your case,

NSDateFormatter *objTimeFotmatter=[[NSDateFormatter alloc]init];
[objTimeFotmatter setDateFormat:@"HH:mm"];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[objTimeFotmatter setLocale:usLocale];

Similarly for all dateformatters.

Ilanchezhian
  • 17,426
  • 1
  • 53
  • 55
3

Swift

let dateFormatter = DateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US") as Locale!
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
let resultsDate = dateFormatter.string(from: date)
Musa almatri
  • 5,596
  • 2
  • 34
  • 33
1

Try with this code:

NSDate *date=[NSDate date];
NSDateFormatter *objTimeFotmatter=[[NSDateFormatter alloc]init];
[objTimeFotmatter setDateFormat:@"HH:mm"];
[objTimeFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]
autorelease]];
NSDateFormatter *objDayFotmatter=[[NSDateFormatter alloc]init];
[objDayFotmatter setDateFormat:@"EEEE"];
[objDayFotmatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]
autorelease]];
NSString *objTime=[objTimeFotmatter stringFromDate:date];
NSString *objDay=[objDayFotmatter stringFromDate:date];
[objDayFotmatter release];
[objTimeFormatter release];

NSLog(@"objTime=%@",objTime);
NSLog(@"objDay=%@",objDay);
halfer
  • 19,824
  • 17
  • 99
  • 186
Parth Bhatt
  • 19,381
  • 28
  • 133
  • 216