Home > Mobile >  How to get the difference betweeen two dates (jetpack compose/kotlin)?
How to get the difference betweeen two dates (jetpack compose/kotlin)?

Time:09-05

I have to calculate how many days are left between the date selected by the user through a DatePicker and the current date

I was trying to write something like this:

val simpleDate = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
val date = simpleDate.parse(event!!.date!!)
val diff = Duration.between(LocalDate.now(), date.toInstant())
val leftDays = diff.toDays()

CodePudding user response:

Try below code -

        val previousTimeDouble: Double = previousTime.toDouble()
        val nowTimeDouble: Double = System.currentTimeMillis().toDouble()
        val dateNowString: String = dateNow.toString();

        val time: Long = (nowTimeDouble - previousTimeDouble).toLong()

        val difference: String= differenceBetweenTwoTimes(time)

        Log.d("difference", difference)

Function for converting time difference into units -

fun differenceBetweenTwoTimes(time: Long): String {
            var x: Long = time / 1000
            var seconds = x % 60
            x /= 60
            var minutes = x % 60
            x /= 60
            var hours = (x % 24).toInt()
            x /= 24
            var days = x
            return String.format("d:d:d", hours, minutes, seconds)
        }

CodePudding user response:

Your mix of outdated (SimpleDateFormat, 'Date') and modern (LocalDate) APIs is not optimal, I think:

I would use plain java.time here, because…

  • you can obviously use it in your application
  • it has a specific class for datetime Strings of the pattern you have shown in your question: an OffsetDateTime and
  • there's a java.time.Duration which you have tried to use

Here's an example:

fun main(args: Array<String>) {
    // example input, some future datetime
    val input = "2022-12-24T13:22:51.837Z"
    // parse that future datetime
    val offsetDateTime = OffsetDateTime.parse(input)
    // build up a duration between the input and now, use the same class
    val duration = Duration.between(OffsetDateTime.now(), offsetDateTime)
    // get the difference in full days
    val days = duration.toDays()
    // print the result as "days left"
    println("$days days left")
}

Output:

110 days left

If you don't receive a datetime but a date without time (just day of month, month of year and year), then use a LocalDate and calculate the ChronoUnit.DAYS.between(today, futureDate)

fun main(args: Array<String>) {
    // example input, some future date
    val input = "2022-12-24"
    // parse that
    val futureDate = LocalDate.parse(input)
    // get the difference in full days
    val days = ChronoUnit.DAYS.between(LocalDate.now(), futureDate)
    // print the result
    println("$days days left")
}

Output (again):

110 days left
  • Related