【问题标题】:Why does formatting a date using DateTimeFormatter with a YYYY pattern give the wrong year? [duplicate]为什么使用带有 YYYY 模式的 DateTimeFormatter 格式化日期会给出错误的年份? [复制]
【发布时间】:2018-07-02 18:36:57
【问题描述】:

DateTimeFormatter(使用下面的模式)与LocalDate 一起使用会导致错误的年份。

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

DateTimeFormatter format = DateTimeFormatter.ofPattern("MM-d-YYYY");
LocalDate date = LocalDate.of(2018, 12, 31);

date.format(format); // returns 12-31-2019 (expected 2018)

为什么会这样?

【问题讨论】:

    标签: java time date-formatting


    【解决方案1】:

    发生这种情况是因为MM-d-YYYY 不是我们想象的那样。

    如果我们查看the documentation,我们会看到

     Symbol  Meaning                     Presentation      Examples  
     ------  -------                     ------------      -------  
     y       year-of-era                 year              2004; 04  
     Y       week-based-year             year              1996; 96
    

    所以YYYY 使用的是基于周的年份,而我们实际上想要的是yyyy,即时代的年份。

    请参阅 this related questionthe Wikipedia article on week dates 了解区别。

    所以我们想要的模式是MM-d-yyyy

    【讨论】:

    • 我们有一个 java 程序运行良好 8 个月,然后由于 YYYY 问题而在一年中的最后一周失败。 (最后一周是在圣诞节和新年之间,当时一半的开发人员都在休假。)我将 YYYY 更改为 yyyy,它给了我正确的年份。谢谢kag0
    • 这篇博文有一个很好的代码示例,说明了 YYYY 和 yyyy 的区别 - dangoldin.com/2019/01/06/javas-simpledateformat-yyyy-vs-yyyy
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    相关资源
    最近更新 更多