3

For example, I'd have two dates as expected in the function.

val period = Period.between(date1, date2)

What is returned is a String like this "P*y*Y*x*M*z*D" where y is the year, x is the month and z is the day. I want to store each of these values in separate variables.

At first I tried using .split() but I couldn't find a way to account for all the letters.

It's worth mentioning as well that if the period between the two dates is less than a year for example, the returned string would be "P*x*M*z*D". Same goes for the month as well. So how can I extract this information while accounting for all the possible formats of the returned String?

deHaar
  • 17,687
  • 10
  • 38
  • 51
berry
  • 43
  • 2
  • 5
    Why are you trying to parse the string? How about just use the `Period` as a `Period`? – Sweeper Mar 14 '23 at 08:44
  • 3
    _"What is returned is a string"_ - no! What is returned is a [Period](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/Period.html). – DodgyCodeException Mar 14 '23 at 09:02
  • 1
    Don't confuse the `toString()` representation of the `Period` with the `Period` object itself. And if for some reason you start out with only a string in the described format, don't try to parse it yourself; just use [`Period#parse(CharSequence)`](https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/time/Period.html#parse(java.lang.CharSequence)) and get the values you need from the returned `Period` object. – Slaw Mar 14 '23 at 09:10

2 Answers2

7

A Period has fields that can be accessed:

fun main() {
    val date1 = LocalDate.of(2023, 1, 3)
    val date2 = LocalDate.of(2023, 3, 5)
    val period = Period.between(date1, date2)
    println("years: ${period.years}, months: ${period.months}, days: ${period.days}")
}

Output:

years: 0, months: 2, days: 2
deHaar
  • 17,687
  • 10
  • 38
  • 51
1

Period class has method get (https://docs.oracle.com/javase/8/docs/api/java/time/Period.html#get-java.time.temporal.TemporalUnit-) which can give you desired information:

val period = Period.between(date1, date2)
val years = period.get(ChronoUnit.YEARS)
val months = period.get(ChronoUnit.MONTHS)
val days = period.get(ChronoUnit.DAYS)
Nikolai Shevchenko
  • 7,083
  • 8
  • 33
  • 42