Reputation: 59
I've been facing a problem and I can't figure out how to solve it properly.
// Imagine these values are timestamps
val comboStart: Long = 7pm day 1
val comboEnd: Long = 1am day 2
fun foo() {
if (differenceBetweenTimestamps() > 1) {
println("Day changed")
} else {
println("Still the same day")
}
}
fun differenceBetweenTimestamps(): Long {
return TimeUnit.MILLISECONDS.toDays(comboEnd - comboStart)
}
The problem with this piece of code is that it will only tell me that the day changed if the difference between two timestamps is greater than one day, but as you can see I declared 2 timestamps with a difference lower than 24 hours between them, even though the day changed in this scenario.
Any idea how can I solve this?
Upvotes: 1
Views: 1647
Reputation: 66
As the Timeunit.MILLISECONDS starts Midnight January 1, 1970 UTC, I would suggest you divide (long division) millisecond value by the milliseconds per day (should be 86400000). If the result differs by 1, the day changed.
So instead of TimeUnit.MILLISECONDS.toDays(comboEnd - comboStart) try TimeUnit.MILLISECONDS.toDays(comboEnd) - TimeUnit.MILLISECONDS.toDays(comboStart)
Upvotes: 1