kotlindatesplitperiod

How can I extract information from the string returned in Period.between()? (Kotlin)


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?


Solution

  • 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