MohammadBaqer
MohammadBaqer

Reputation: 1415

How to compare LocalDateTime instances in kotlin

so I'm having a little problem with kotlin LocalDateTime

val now = CurrentDateTime
val someDate = someService.someLocalDateTime

I have two dates as you can see and I want to know if now is bigger than someDate or not. and also I need to know if it's bigger, how much is bigger.

i can do it by checking year, month, day, minute and second like this:

if (now.year().toString() == someDate.year.toString())

but it's not a good way

any suggesstions would be welcome.

Upvotes: 1

Views: 4431

Answers (4)

MakiX
MakiX

Reputation: 446

If you are using kotlinx-datetime, I think you can compare them as you will do for Number or String:

// Check if startDate is before endDate.

val datesAreValid = startDate < endDate

I'm not sure it compares something using the LocalDate Object or the String that prints. What I see is it print "2024-02-09" when as String.

If < > = on String compares case by case we can assume "2024-02-09" is less than "2024-03-09".

It's Years / Month / day order and ****-**-** good format like he will persit 2 cases all the time.

Upvotes: 1

Enowneb
Enowneb

Reputation: 1037

Convert Kotlin LocalDateTime to Java LocalDateTime

To convert Kotlin LocalDateTime to Java LocalDateTime, you can make use of this function:

fun LocalDateTime.toJavaLocalDateTime(): LocalDateTime

Converts this kotlinx.datetime.LocalDateTime value to a java.time.LocalDateTime value.

And then you can choose to use the following method or other suggested method to compare the converted java.time.LocalDateTime.

Compare Java LocalDateTime

To compare LocalDateTime, you can use LocalDateTime's isAfter(), isBefore(), isEqual().

import java.time.LocalDateTime

fun main() {
    val currentTime = LocalDateTime.now()
    val ytdTime = LocalDateTime.now().minusDays(1)
    println(currentTime.isAfter(ytdTime))
    println(currentTime.isBefore(ytdTime))
    println(currentTime.isEqual(ytdTime))
}

Output

true
false
false

To find the difference between LocalDateTime, you can use ChronoUnit:

import java.time.temporal.ChronoUnit

fun main() {
    val currentTime = LocalDateTime.now()
    val ytdTime = LocalDateTime.now().minusDays(1)
    val secondDifference = ChronoUnit.SECONDS.between(ytdTime, currentTime)
    val minutesDifference = ChronoUnit.MINUTES.between(ytdTime, currentTime)
    val hourDifference = ChronoUnit.HOURS.between(ytdTime, currentTime)
    println(secondDifference)
    println(minutesDifference)
    println(hourDifference)
}

Output

86399
1439
23

Upvotes: 3

Messerhi djalal
Messerhi djalal

Reputation: 41

The standard solution to compare two Date objects is by using the compareTo() function. It returns a value

= 0, if both dates are equal.
< 0, if date is before the specified date.
> 0, if date is after the specified date.

The following program demonstrates it:

import java.text.SimpleDateFormat
import java.util.*

 
fun main() {

    val now = CurrentDateTime  // "01/21/2023" 
    val someDate = someService.someLocalDateTime // "01/21/2020"
 
    val sdf = SimpleDateFormat("MM/dd/yyyy")
 
    val firstDate: Date = sdf.parse(now)
    val secondDate: Date = sdf.parse(someDate)
 
    val cmp = firstDate.compareTo(secondDate)
    when {
        cmp > 0 -> {
            System.out.printf("%s is after %s", d1, d2)
        }
        cmp < 0 -> {
            System.out.printf("%s is before %s", d1, d2)
        }
        else -> {
            print("Both dates are equal")
        }
    }
}

Upvotes: 3

Mirco0
Mirco0

Reputation: 321

You can simply convert both dates in seconds and:

  • compare them to know which one is bigger
  • subtract them to know how much one is bigger than the other

an example would be

val now = CurrentDateTime.toEpochSeconds()
val someDate = someService.someLocalDateTime.toEpochSeconds();

if(now > someDate) 
//someDate is in the past
else
//someDate is in the future or both dates are equal

val distance = now-someDate

hope this helps

Upvotes: 3

Related Questions