'scala get difference between two dates in number of days
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?
Solution 1:[1]
What you are looking for is the LocalDate.until() method with unit set to ChronoUnit.DAYS:
import java.time.LocalDate
import java.time.temporal.ChronoUnit
val date1 = LocalDate.parse("2022-04-01")
val date2 = LocalDate.parse("2022-05-03")
val daysBetween = date1.until(date2, ChronoUnit.DAYS)
// scala> date1.until(date2, ChronoUnit.DAYS)
// res1: Long = 32
Note that your first attempt does simple lexicographical string comparison which is oblivious to the fact that your strings are dates. The return value of String.compareTo() (and Comparable<T>.compareTo() in general) is to be interpreted only on the basis whether it is 0, < 0, or > 0. The actual value is meaningless in most cases. The fact that it matches the actual number of days in your first example is due to how your dates are formatted and to how String.compareTo() works:
In this case,
compareToreturns the difference of the two character values at position k in the two string [sic]
Here, k refers to the position where the two strings first differ.
Your second attempt with Period doesn't work either because Period represents conceptual differences. Adding P1M3D to some date means incrementing the month by one and the day by three, therefore the length in days is dependent on the month to which it is being applied:
2022-04-01 + P1M3D = 2022-05-04 -> 33 days
2022-05-01 + P1M3D = 2022-06-04 -> 34 days
Thus, a freestanding Period object has no length in days (unless it only has days but not months or years) and the getDays accessor returns only the days component, not the full number of days.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
