Khant Thu Linn
Khant Thu Linn

Reputation: 6143

NSDateFormatter for Chinese date

I have watched Advanced topics ininternationalization in WWDC 2014 and they recommend like this. Also, we can use custom format for different language.So, I am doing like this.

if([[Helpers getLocale]isEqualToString:@"zh-Hans"] || [[Helpers getLocale]isEqualToString:@"zh-Hant"])
{
    formatDate.dateFormat = @"yyyy MMM d"; //TODO: how to set for Chinese? dd also not okay
}
else
{   //Default as English..en
    formatDate.dateFormat = @"d MMM yyyy";
}

However, for chinese language, I cannot set properly and I only get this. 2014 8月 22. How can I set format for Chinese Date as shown in first picture? (with custom format)

enter image description here

enter image description here

Upvotes: 2

Views: 2728

Answers (3)

Trần Thị Diệu My
Trần Thị Diệu My

Reputation: 1423

Please try this code

NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_Hant_HK"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:locale];
[dateFormatter setDateStyle:NSDateFormatterFullStyle];
//[dateFormatter setTimeStyle:NSDateFormatterShortStyle];//if you want show time, please enable this line

NSDate *date = [NSDate date];
NSString* str = [dateFormatter1 stringFromDate:date];

Upvotes: 0

Mev
Mev

Reputation: 1625

You should use dateFormatFromTemplate method. This will take in your preferred date format and convert it to locale's format. This will introduce any additional special characters if it must and you do not have to worry about it.
As an example this is what I do to convert my preferred format of "dd MMM yyyy" to the equivalent format in Chinese languages.

// input format in this case is "dd MMM yyyy"
// when language is set to Chinese, I will change it accordingly like this. 

NSLocale *locale = [NSLocale currentLocale];
    NSString *language = [locale objectForKey:NSLocaleLanguageCode];
    if ([language containsString:@"zh"])
    {
        format = [NSDateFormatter dateFormatFromTemplate:format options:0 locale:locale];
    }
// output format from this code for chinese languages is yyyy年M月dd日 

You do not have to manually insert / remove special characters. Hope this helps

Upvotes: 3

Khant Thu Linn
Khant Thu Linn

Reputation: 6143

It is because I don't know Chinese language. We can use this format. y年M月d日

Upvotes: 4

Related Questions