0

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?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Bazzoner
  • 59
  • 2
  • 7
  • 2
    While I think that this is not a strict duplicate, there are some related questions: (1) [Invalid date is populated when we use yyyy-MM-dd'T'HH:mm:ssXXX format in java \[duplicate\]](https://stackoverflow.com/questions/54918883/invalid-date-is-populated-when-we-use-yyyy-mm-ddthhmmssxxx-format-in-java) (2) [Why does Java's java.time.format.DateTimeFormatter#format(LocalDateTime) add a year?](https://stackoverflow.com/questions/34521733/why-does-javas-java-time-format-datetimeformatterformatlocaldatetime-add-a-y) – Ole V.V. Jun 03 '20 at 14:10
  • 1
    Also try `virtualToday.plusYears(1)`. In British Locale (`Locale.UK`) we get `2016-01-01` but `1 January 2015`. It’s one year short. – Ole V.V. Jun 03 '20 at 17:23

1 Answers1

6

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

akuzminykh
  • 4,522
  • 4
  • 15
  • 36
  • Thanks. Knew it would be something daft I as doing. – Bazzoner Jun 03 '20 at 11:56
  • 3
    In addition, use a `y` and not a `Y` if you want the year of era and not the week-based year. – deHaar Jun 03 '20 at 11:57
  • 2
    @deHaar That’s actually an important addition, thank you. While this error might go unnoticed for long, it will certainly confuse users when it surfaces eventually. Which it will. – Ole V.V. Jun 03 '20 at 14:12