【问题标题】:Remove year from NSDateFormatterFullStyle string从 NSDateFormatterFullStyle 字符串中删除年份
【发布时间】:2013-06-20 04:57:45
【问题描述】:

我已经搜索了这个问题,但没有找到一个确凿而优雅的解决方案。无论如何要更改 NSDateFormatterFullStyleyear 以抑制年份信息。我正在使用代码:

    NSString *dateDescription;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    [dateFormatter setTimeZone:gmt];
    [dateFormatter setDateStyle:NSDateFormatterFullStyle];
    dateDescription = [dateFormatter stringFromDate:date];
    NSLog(@"%@", dateDescription);

结果:2013 年 3 月 13 日,星期三

问候, 马科斯

【问题讨论】:

  • 只是带有 dateDescription = [dateDescription substringWithRange:NSMakeRange(0, dateDescription.length-6); 的子字符串
  • @ices_2 如果用户的语言环境将日期放在字符串末尾以外的位置,那将无法正常工作。
  • 但字符串可能因定义的用户语言环境而异。
  • [dateFormatter setDateFormat:@"EEEE, MMMM d"];
  • @ices_2 但是这样做会阻止日期在用户当前的语言环境中正确显示。

标签: ios objective-c nsdate nsdateformatter


【解决方案1】:

以下是最接近的,无需大量棘手的字符串处理。对dateFormatFromTemplate:options:locale: 的调用将更新提供的模板以最好地匹配指定的语言环境。

这假定正常的“完整”样式为您提供工作日名称、月份名称和月份中的日期。

NSString *fullMinusYear = [NSDateFormatter dateFormatFromTemplate:@"EEEE, MMMM dd" options:0 locale:[NSLocale currentLocale]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:fullMinusYear];
NSString *dateDescription = [dateFormatter stringFromDate:date];

【讨论】:

  • @user2384694 添加日期的方法相同。只需添加您想要的任何与时间相关的格式说明符。如果您无法弄清楚,请发布您自己的问题,并附上您尝试过的操作和遇到的问题的相关详细信息。
猜你喜欢
  • 1970-01-01
  • 2012-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-26
  • 2013-09-18
相关资源
最近更新 更多