【问题标题】:Using NSDateFormatter to convert Int to Month String使用 NSDateFormatter 将 Int 转换为 Month String
【发布时间】:2015-11-11 18:19:15
【问题描述】:

我一直在这里使用另一个答案来做到这一点。我将我的日期作为 Int 存储在我的数据库中,但我希望它在 UI 中显示为整月。因此,在刷新/重新加载时,我试图获取 Int 月份值 -> 转换为字符串整月 -> 在文本字段中显示。

我目前已将其注销月份和完整日期,但在重新加载时的文本字段中显示为 (null) / 05 / 1993

我做错了什么??

NSString *monthString = [self.datePickerFormat monthSymbols] [(self.birthdayMonth - 1)];
NSLog(@"%@",monthString);

NSString *dateString = [NSString stringWithFormat:@"%@ / %ld / %ld",monthString,(long)self.birthdayDay,(long)self.birthdayYear];
NSLog(@"%@",dateString);

self.birthdayField.text = [NSString stringWithFormat:@"%@",dateString];

self.birthdayMonth 是一个整数。 self.datePickerFormat 是我已声明为属性的 NSDateFormatter。编辑:好的,日志没有返回正确的月份,所以我不知道发生了什么..

还有其他更好的方法吗?感谢您的帮助!

【问题讨论】:

  • datePickerFormat 未初始化。
  • 仅供参考 - 使用 stringWithFormat 构建日期字符串是一个非常糟糕的主意。使用NSDateFormatter,以便为用户的区域设置正确的日期格式。

标签: ios objective-c nsdateformatter


【解决方案1】:

要从月份编号中获取月份名称,请以这种方式使用日期格式化程序:

NSInteger month = 7;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSString *monthString = dateFormatter.monthSymbols[(month-1)];

月份名称将以您的手机区域设置语言显示。虽然不建议这样做,但您可以覆盖区域设置:

dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US"];

【讨论】:

    猜你喜欢
    • 2017-07-29
    • 1970-01-01
    • 2014-07-29
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-05
    相关资源
    最近更新 更多