Java 8 LocalDate.plusMonths is adding to days and months

喜夏-厌秋 提交于 2021-02-05 11:39:21

问题


I'm getting strange formatting issue when adding months to a LocalDate. Here is the Scala code and output:

val virtualToday: LocalDate = LocalDate.parse("2015-01-01")
val eightDaysFromToday: LocalDate = virtualToday.plusDays(8)
val sixMonthsFromToday: LocalDate = virtualToday.plusMonths(6)

println("virtualToday " + virtualToday)
println("eightDaysFromToday " + eightDaysFromToday)
println("sixMonthsFromToday " + sixMonthsFromToday)

println(
      "virtualToday with formatting " + virtualToday
        .format(DateTimeFormatter.ofPattern("D MMMM Y"))
    )
println(
      "eightDaysFromToday with formatting " + eightDaysFromToday
        .format(DateTimeFormatter.ofPattern("D MMMM Y"))
    )
println(
      "sixMonthsFromToday with formatting " + sixMonthsFromToday
        .format(DateTimeFormatter.ofPattern("D MMMM Y"))
    )

and this is the output:

virtualToday 2015-01-01
eightDaysFromToday 2015-01-09
sixMonthsFromToday 2015-07-01

virtualToday with formatting 1 January 2015
eightDaysFromToday with formatting 9 January 2015
sixMonthsFromToday with formatting 182 July 2015

As you can see it is correctly adding 6 months to the month but it's also adding 6 months to the days too. How do I get the formatted sixMonthsFromToday date as 1 July 2015?


回答1:


Check out DateTimeFormatter. The D is for day-of-year. If you want day-of-month use d.



来源:https://stackoverflow.com/questions/62172174/java-8-localdate-plusmonths-is-adding-to-days-and-months

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!