How to make NSDateFormatter display locale-specific date?

荒凉一梦 提交于 2019-12-18 12:20:54

问题


I am using NSDateFormatter to set my date in my iPhone app, and dates are showing up properly. However, I am finding all the locales (my app supports up to 12 different languages) are sticking to the date format I specify via setDateFormat. Ideally, I want the date format to appear in a form natural to the region setting for the user, instead of following my format (which works well for English but may not be natural for other locales).

Following is my code:

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    [dateFormatter setDateFormat:@"MMMM dd, yyyy kk:mm:ss"];

    self.creationDate.text = [dateFormatter stringFromDate:creationTimeStamp];

回答1:


I would try the following NSDateFormatter API instead:

+ (NSString *)localizedStringFromDate:(NSDate *)date
              dateStyle:(NSDateFormatterStyle)dateStyle
              timeStyle:(NSDateFormatterStyle)timeStyle;

Like so:

self.creationDate.text = [NSDateFormatter localizedStringFromDate:creationTimeStamp
                                          dateStyle:NSDateFormatterMediumStyle
                                          timeStyle:NSDateFormatterShortStyle];

That should give you the output you're looking for, tidy up the code a little, and keep you from having to manage some spurious memory.




回答2:


Found the solution. The key is to not call setDateFormat at all, and the API in iPhone would automatically pick the appropriate thing to display based on what is specified in setDateStyle and setTimeStyle.




回答3:


Self-contained solution with @fbrereto's design:

static NSString *FormatDate(NSDate *date)
{
  return [NSDateFormatter localizedStringFromDate:date
                                        dateStyle:NSDateFormatterMediumStyle
                                        timeStyle:NSDateFormatterNoStyle];
}

Now you can simply run:

NSString *formattedDate = FormatDate([NSDate new]);


来源:https://stackoverflow.com/questions/1348590/how-to-make-nsdateformatter-display-locale-specific-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!