代码之家  ›  专栏  ›  技术社区  ›  kag0

为什么使用带有yyyy模式的datetimeformatter格式化日期会给出错误的年份?[副本]

  •  0
  • kag0  · 技术社区  · 6 年前

    使用 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)
    

    为什么会这样?

    1 回复  |  直到 6 年前
        1
  •  1
  •   kag0    6 年前

    这是因为 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 question the Wikipedia article on week dates 为了区别。

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