【问题标题】:NSDateFormatter - Adding a Year? [duplicate]NSDateFormatter - 添加一年? [复制]
【发布时间】:2014-12-30 06:28:34
【问题描述】:

我有以下代码,它只是获取当前日期并将其转换为格式 YYYY-MM-dd HH:mm:ss zzz

        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat: @"YYYY-MM-dd HH:mm:ss zzz"];
        NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
        [dateFormatter setTimeZone:currentTimeZone];

        NSString *time = [dateFormatter stringFromDate:[NSDate date]];

        NSLog(@"TIME IS %@", time);

有了这个,我得到以下日志输出:

2014-12-30 00:20:38.987 MYAPPNAME[953:229825] TIME IS 2015-12-30 00:20:38 CST

有人能告诉我为什么输出显示为 2015 年,而不是应有的 2014 年吗?

【问题讨论】:

  • 检查您的系统或设备日期
  • 在日期格式中使用yyyy 而不是YYYY
  • @AdamTheRaysFan:请接受并投票支持对您有帮助的答案。

标签: ios objective-c xcode nsdateformatter


【解决方案1】:

yyyy 指定日历年,而YYYY 指定年份(“一年中的一周”)

你必须改变你的dateformatter风格

[dateFormatter setDateFormat: @"YYYY-MM-dd HH:mm:ss zzz"];

[dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss zzz"];

供您参考,请查看apple documentation

【讨论】:

    【解决方案2】:

    更改日期格式

    [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss zzz"];
    

    【讨论】:

      【解决方案3】:

      试试这个:

              NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
              [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss zzz"];
              NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
              [dateFormatter setTimeZone:currentTimeZone];
      
              NSString *time = [dateFormatter stringFromDate:[NSDate date]];
      
              NSLog(@"TIME IS %@", time);
      

      有关 NSDateFormatter 的更多详细信息,请阅读以下内容:

      http://realmacsoftware.com/blog/working-with-date-and-time

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-05
        • 1970-01-01
        • 2014-04-02
        相关资源
        最近更新 更多