Search code examples
iphoneios4ios5nsdatensdateformatter

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=ગુરુવાર

Solution

  • 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.