berry
berry

Reputation: 43

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?

Upvotes: 3

Views: 125

Answers (2)

deHaar
deHaar

Reputation: 18588

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

Upvotes: 7

Nikolai  Shevchenko
Nikolai Shevchenko

Reputation: 7521

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)

Upvotes: 1

Related Questions