Cocoa - Localized string from NSDate, NSCalendarDa

2020-02-23 04:36发布

I'm using NSDate to get a string such as "18 Jun 09", with code:

NSDate *theDate = [NSDate date];
NSString *dateString = [theDate descriptionWithCalendarFormat:@"%d %b %y"
        timeZone:nil
        locale: nil];

This works, but only results in an English output. I need the output to be localized in the user's default language.

Does Cocoa (Mac OS X 10.4, 10.5 in this case) provide a facility for this localization or do I have to manually localize for each case of day and & month names my self?

(I have provided a locale, but although that does provide a locale-specific ordering of the date, it does not appear to do any localization of day-month names.)

2条回答
孤傲高冷的网名
2楼-- · 2020-02-23 04:56

Here is a snippet from Apple:

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];

[dateFormatter setDateStyle:NSDateFormatterMediumStyle];

[dateFormatter setTimeStyle:NSDateFormatterNoStyle];

NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:118800];

NSString *formattedDateString = [dateFormatter stringFromDate:date];

NSLog(@"formattedDateString for locale %@: %@", [[dateFormatter locale] localeIdentifier], formattedDateString);
查看更多
叼着烟拽天下
3楼-- · 2020-02-23 05:18

It appears one line of code is missing:

[dateFormatter setLocale:usLocale];
查看更多
登录 后发表回答