AlbertB
AlbertB

Reputation: 637

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.

Upvotes: 3

Views: 2272

Answers (2)

Anonymous
Anonymous

Reputation: 86232

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.

Upvotes: 3

Mario Burga
Mario Burga

Reputation: 1157

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.

Upvotes: 1

Related Questions