Skip to content
Advertisement

How to get days remaining of a date and print hours minutes and seconds Java8

I’m getting from server an UTC date for instance

JavaScript

I’d like to know what is the optimal way to calculate remaining days from now.

Here’s what I got now :

I’m creating a date for 2 days from now as :

JavaScript

I’m parsing it to a DateTime joda I can use other if you say so.

When doing the diff of days I’m doing this way

JavaScript

The scenario that I’m trying to achieve is :

If the days remaining is more than one (24h) then print “2 days remaining” for instance, and instead of showing “1 day remaining” then just add a timer as :

“0h 43m 3s”.

To do the timer I’m just subtracting the time remaining with now

JavaScript

And then on every second it happen I print it like this :

JavaScript

But I’m not getting the 2 days, I’m just getting as an output :

JavaScript

So, I’m having some problems here for instance :

Is this an optimal solution? If not could you describe a better one where I can achieve my goal? Why my timer is showing with 00h: 13m: 813s? Am I doing the regex incorrectly or it’s because of epochSeconds?

To achieve

Given an UTC date from server when trying to print it to the device then it should follow this rules.

1.- If days remaining is > than 1 day then print “N days remaining”

2.- If days remaining is <= 1 then print a timer (it’s already done, the thing is how to print it correctly).

  • Minimum 1 digit (0h 2m 1s)
  • Maximum 2 digits (1h 23m 3s)

Note :

I’m using Java 8 I can change also the way I’m doing the countdown to use millis instead of epochSeconds if that’s the problem.

Advertisement

Answer

You could do that using a ZonedDateTime for now and the future datetime, and then calculate a Duration.between instead of calculating remaining seconds first and then use a Duration.ofSeconds().

Here`s a Kotlin example:

JavaScript

Output: 48h: 00m: 00s


If you are interested in remaining full days only, then consider using ChronoUnit.DAYS.between, maybe like this:

JavaScript

Output: 2 days


Additional:

Since it is unclear to me what data type you are trying to use for the calculation of the time left until end of validity, you will have to choose between providing more detailed information in your question or using one of the following funs:

Pass a ZonedDateTime

JavaScript

Pass an Instant

JavaScript

Pass the String directly

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement