【问题标题】:Formatting the month and year in iOS在 iOS 中格式化月份和年份
【发布时间】:2012-11-21 03:43:23
【问题描述】:

我只想在我的 iPad 应用程序中显示当前月份和年份,如“2012 年 11 月”,我目前正在将月份格式化为“MMMM”,将年份格式化为“yyyy”并将它们连接起来。这适用于大多数语言环境,但不适用于“中国”地区。

我当前的代码将“中国”地区的月份和年份显示为,

但是,这是不对的。就像它显示在 iOS 日历应用程序中一样,

关于如何实现这一点的任何想法?

编辑 1:

NSDate *date = [NSDate date];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat=@"MMMM";
NSString * monthString = [[dateFormatter stringFromDate:date] capitalizedString];
dateFormatter.dateFormat=@"yyyy";
NSString * yearString = [[dateFormatter stringFromDate:date] capitalizedString];

lblMonthAndYear.text = [NSString stringWithFormat:@"%@ %@",monthString,yearString];

【问题讨论】:

  • 显示格式化代码
  • 你的意思是“MMMM”而不是“EEE”来获得“十一月”吗?
  • 尝试设置这个,[dateFormatter setLocale:[NSLocale currentLocale]];

标签: ios ipad nsdate nsdateformatter nsdatecomponents


【解决方案1】:

我认为你的日期格式化程序根本没有使用语言环境,这里的关键是使用当前语言环境创建模板,而不仅仅是格式字符串,例如:

NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:@"MMMM d"
                                                       options:0
                                                        locale:[NSLocale currentLocale]];
dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = dateFormat;

【讨论】:

  • 完美!是的,这就是问题所在。不知道如何在此处准确包含语言环境。感谢您提供光速解决方案! @"MMMM yyyy" 成功了。
猜你喜欢
  • 1970-01-01
  • 2017-07-12
  • 1970-01-01
  • 1970-01-01
  • 2011-09-13
  • 2013-10-13
  • 2021-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多