Home > Blockchain >  calculate the difference of days between two dates in kotlin
calculate the difference of days between two dates in kotlin

Time:01-31

I need in my application to be able to calculate the difference of days between two dates. I tried a few ways that would give us the difference between the days of the future, but I need to get the past right as well.

I try with val currentTime = Calendar.getInstance().time

CodePudding user response:

Oh boy, you haven't realized it yet, but you just opened pandoras box: Time is very weird (especially in the past) and it is not as simple as calculating the difference between two timestamps. If you want to understand the insanity, I highly recommend this video by Tom Scott.

But anyway, to your question:

import java.time.Duration
import java.time.LocalDate

val firstTimestampInclusive = LocalDate.of(2000, 2, 27)
val secondTimestampExclusive = LocalDate.of(2000, 3, 1)
val numberOfDays = Duration.between(firstTimestampInclusive.atStartOfDay(), secondTimestampExclusive.atStartOfDay()).toDays()
println("Number of days between $firstTimestampInclusive and $secondTimestampExclusive: $numberOfDays")

This will print the following:

Number of days between 2000-02-28 and 2000-03-01: 2

Edit: For many reasons, using java.util.Date and java.util.Calendar is discouranged and you should use java.time instead (as I usggested in my answer).

CodePudding user response:

val cal = Calendar.getInstance()
cal.time = date1
val day1 = cal.get(Calendar.DAY_OF_YEAR)

val cal2 = Calendar.getInstance()
cal2.time = date2
val day2 = cal2.get(Calendar.DAY_OF_YEAR)

day1 and day2 are integers between 0-365

  • Related