Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nsdateformatter returns me day in language of the phone selected. Can it return me only English all the time?

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=ગુરુવાર
like image 512
breakfreehg Avatar asked Nov 24 '11 06:11

breakfreehg


3 Answers

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.

like image 196
Ilanchezhian Avatar answered Nov 06 '22 12:11

Ilanchezhian


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)
like image 38
Musa almatri Avatar answered Nov 06 '22 13:11

Musa almatri


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);
like image 1
Parth Bhatt Avatar answered Nov 06 '22 12:11

Parth Bhatt