Home > Software design >  Is there any Scala function that gives last date of the month that date belongs?
Is there any Scala function that gives last date of the month that date belongs?

Time:01-25

this is my first question on stack overflow. I have a date as input and output should be last date of the month that falls in.

for example

Input string "01/15/2023" should output "01/31/2023" or "02/10/2021" should output "02/28/2021" 0r

"02/10/2024" should output "02/29/2024" (Incase of leap year) etc all such rules applicable.

I have tried below code through online search of a java , but I am getting error which I am not able to figure it out, please do help me out.

val endDate: ZonedDateTime = ZonedDateTime.parse("2023-01-15")
       println("1A. Last day of the current month: " endDate.toLocalDateTime().with(TemporalAdjusters.lastDayOfMonth())

CodePudding user response:

Trying to parse dates in a ZonedDateTime will not work like that because you are lacking the time zone information. I will use a LocalDate, which more closely models the input, and leave the conversion from LocalDate to ZonedDateTime as a separate problem.

Regardless, you can use the with method on both types and pass java.time.TemporalAdjusters.lastDayOfMonth as in the following example:

import java.time.temporal.TemporalAdjusters

def t(date: String): java.time.LocalDate =
    java.time.LocalDate.parse(date, java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd"))

val tests = Map(
  t("2023-01-15") -> t("2023-01-31"),
  t("2023-09-15") -> t("2023-09-30"),
  t("2024-02-14") -> t("2024-02-29"),
  t("2023-02-14") -> t("2023-02-28"),
)

for ((input, expected) <- tests) {
  val actual = input.`with`(TemporalAdjusters.lastDayOfMonth())
  assert(actual == expected, s"$actual did not equal $expected for input $input")
}

Notice I had to put the call to with between backticks because with is also a keyword in Scala.

You can play around with this code here on Scastie.

You can read more about with here on its JavaDoc, which also points to how to use it together with TemporalAdjusters.

CodePudding user response:

import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.temporal.TemporalAdjusters

val formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy")

val date = LocalDate.parse("02/10/2021", formatter)

val endDate = date.`with`(TemporalAdjusters.lastDayOfMonth())

println(s"last date of month = ${endDate.format(formatter)}")
  • Related