I was trying to calculate the number of days between 2 dates in scala. I tried using compareTo
and import java.time.Period
function. But it is not giving the exact value of days when comparing two dates from different months.
val date1 = "2022-04-01"
date1: String = 2022-04-01
val date2 = "2022-04-04"
date2: String = 2022-04-04
date2.compareTo(date1)
res37: Int = 3
val date2 = "2022-05-04"
date2: String = 2022-05-04
date2.compareTo(date1)
res38: Int = 1
val date1 = LocalDate.parse("2022-04-01")
date1: java.time.LocalDate = 2022-04-01
val date2 = LocalDate.parse("2022-04-04")
date1: java.time.LocalDate = 2022-04-04
val p = Period.between(date1, date2)
p: java.time.Period = P3D
p.getDays
res39: Int = 3
val date2 = LocalDate.parse("2022-05-04")
date2: java.time.LocalDate = 2022-05-04
val p = Period.between(date1, date2)
p: java.time.Period = P1M3D
p.getDays
res40: Int = 3
I want to get the difference as 33 days while comparing the dates 2022-04-01
and 2022-05-04
. Is there a different way to achieve this?