问题
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