Amir Hosein Musavi
Amir Hosein Musavi

Reputation: 31

calculate the difference of days between two dates in kotlin

I need to 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

Upvotes: 0

Views: 4123

Answers (2)

vatbub
vatbub

Reputation: 3119

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).

Upvotes: 6

Eren Enc
Eren Enc

Reputation: 64

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

Upvotes: -1

Related Questions