Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference Between Two localDate

I have a date returned by a json, it is in the following variable as string:

val dateEvent = "2019-12-28 21:00:00"

The calculation I need is to know how many days hours minutes are left with the current date.

I have found some solutions but these use as input "2019-12-28" and I have my format with the time included.

like image 846
AlbertB Avatar asked Jul 14 '26 16:07

AlbertB


2 Answers

java.time

Since Java 9 you can do (sorry that I can write only Java code):

    DateTimeFormatter jsonFormatter = DateTimeFormatter.ofPattern("u-M-d H:mm:ss");
    String dateEvent = "2019-12-28 21:00:00";
    Instant eventTime = LocalDateTime.parse(dateEvent, jsonFormatter)
            .atOffset(ZoneOffset.UTC)
            .toInstant();
    Duration timeLeft = Duration.between(Instant.now(), eventTime);
    System.out.format("%d days %d hours %d minutes%n",
            timeLeft.toDays(), timeLeft.toHoursPart(), timeLeft.toMinutesPart());

When I ran the code just now, the output was:

145 days 4 hours 19 minutes

In Java 6, 7 and 8 the formatting of the duration is a bit more wordy, search for how.

Avoid SimpleDateFormat and friends

The SimpleDateFormat and Date classes used in the other answer are poorly designed and long outdated. In my most honest opinion no one should use them in 2019. java.time, the modern Java date and time API, is so much nicer to work with.

like image 144
Ole V.V. Avatar answered Jul 17 '26 16:07

Ole V.V.


Use the following function:

fun counterTime(eventtime: String): String {
    var day = 0
    var hh = 0
    var mm = 0
    try {
        val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        val eventDate = dateFormat.parse(eventtime)
        val cDate = Date()
        val timeDiff = eventDate.time - cDate.time

        day = TimeUnit.MILLISECONDS.toDays(timeDiff).toInt()
        hh = (TimeUnit.MILLISECONDS.toHours(timeDiff) - TimeUnit.DAYS.toHours(day.toLong())).toInt()
        mm =
            (TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff))).toInt()
    } catch (e: ParseException) {
        e.printStackTrace()
    }

    return if (day == 0) {
        "$hh hour $mm min"
    } else if (hh == 0) {
        "$mm min"
    } else {
        "$day days $hh hour $mm min"
    }
}

counterTime(2019-08-27 20:00:00)

This returns 24 days 6 hour 57 min

Note: The event date should always be a future date to the current date.

like image 30
Mario Burga Avatar answered Jul 17 '26 14:07

Mario Burga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!