Question

From my locale i am getting Chinese date in iPhone, i need to convert that into English using NSDateFormatter. I have tried using the code below, but in the response, i am getting Chinese words also.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh-Hans"]];
[dateFormatter setDateFormat:@"yyyy年MM月dd日'"];
NSDate *dateTmp  = [dateFormatter dateFromString:@"2014年3月14日"]; // getting date from string with english locale
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
NSString *strDate = [dateFormatter stringFromDate:dateTmp]; // getting string from date with spanish locale
NSLog(@"%@",strDate);

This is the output it is showing 2014年3月14日, however i don't need Chinese words in that.

Was it helpful?

Solution

You have to also give the date formate of english as below

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh-Hans"]];
[dateFormatter setDateFormat:@"yyyy年MM月dd日'"];
NSDate *dateTmp  = [dateFormatter dateFromString:@"2014年3月14日"]; // getting date from string with english locale
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSString *strDate = [dateFormatter stringFromDate:dateTmp]; // getting string from date with spanish locale

NSLog(@"Your OUTPUT IS : %@",strDate);

Your OUTPUT IS : 2014-03-14

OTHER TIPS

Try with following code

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh-Hans"]];
    [dateFormatter setDateFormat:@"yyyy年MM月dd日'"];
    NSDate *dateTmp  = [dateFormatter dateFromString:@"2014年3月14日"]; // getting date from string with english locale

    NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
    [dateFormatter2 setDateFormat:@"yyyy MM dd'"];
    [dateFormatter2 setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    NSString *strDate = [dateFormatter2 stringFromDate:dateTmp]; // getting string from date with spanish locale
    NSLog(@"%@",strDate);

You can use next method to get localized format based on template:

NSString *neededFormat = [NSDateFormatter dateFormatFromTemplate:@"MMMM dd, yyyy" options:0 locale:[NSLocale currentLocale]];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top