kokoko
kokoko

Reputation: 3982

date difference in millis to localdatetime

I need to print date again after i calculated difference between two dates.

here is what I tried:

 fun getRemainingTime(endTime: ZonedDateTime): Long {
        val currentTime = ZonedDateTime.now(ZoneId.systemDefault())

        return dateUtils.durationDifference(currentTime, endTime).toMillis()
    }

but when I try to convert it to localdate like below again it starts with 1970. So I need to actual date which was calculated. for example: difference between 2022-10-10 and 2022-10-12 should be 2022-10-02

LocalDateTime.ofInstant(Instant.ofEpochMilli(remainingDurationInMillis), ZoneId.systemDefault())

Upvotes: 1

Views: 91

Answers (1)

Kirill Simonov
Kirill Simonov

Reputation: 8491

java.time.LocalDateTime was not created to represent a difference between two dates. There are java.time.Period and java.time.Duration that should be used for it (see Oracle docs).

A Duration measures an amount of time using time-based values (seconds, nanoseconds). A Period uses date-based values (years, months, days).

They both have a convenient .between() method, which you could use like this:

Duration diff = Duration.between(ZonedDateTime.now(ZoneId.systemDefault()), endTime);

The reason why there are no combined classes to represent duration as years, months, days AND hours, minutes, seconds is that a day could be 24 or 25 hours depending on Daylight saving time. So

A Duration of one day is exactly 24 hours long. A Period of one day, when added to a ZonedDateTime, may vary according to the time zone. For example, if it occurs on the first or last day of daylight saving time.

I would suggest you to use the Duration class and if you want to pretty print it, you have to do it manually like this (thanks to this answer):

System.out.println(diff.toString()
            .substring(2)
            .replaceAll("(\\d[HMS])(?!$)", "$1 ")
            .toLowerCase());

This will print something like 370h 24m 14.645s. If you want days, months and years, you would have to calculate them from seconds and print.

If you're using Java 9+ there are methods to get number of days, hours, minutes and seconds in the duration:

System.out.println(String.format("%sd %sh %sm %ss", 
            diff.toDaysPart(), 
            diff.toHoursPart(), 
            diff.toMinutesPart(), 
            diff.toSecondsPart()));

Upvotes: 4

Related Questions