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=ગુરુવાર
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.
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)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With