How to make NSDateFormatter display locale-specific date?

前端 未结 3 1680
盖世英雄少女心
盖世英雄少女心 2020-12-30 06:35

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 lan

相关标签:
3条回答
  • 2020-12-30 07:02

    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.

    0 讨论(0)
  • 2020-12-30 07:23

    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.

    0 讨论(0)
  • 2020-12-30 07:25

    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]);
    
    0 讨论(0)
提交回复
热议问题