-3

So i am creating an application to countdown to a date in java.

So lets say i parse these 2 days:

Date Now = 2016/01/15 16:52:22
Date End = 2016/01/15 18:37:18

How would i calculate the differences so that i can get the output like so:

1 hour, 44 minutes and 56 seconds

instead of the total hours, total minutes and total seconds.

I guess the best way to explain it is that i need to get the seconds left of the minute, the minutes left of the hour, etc, etc.

azurefrog
  • 10,785
  • 7
  • 42
  • 56
Fable
  • 1
  • 1
  • 2
  • That depends on how you're storing your dates. Are you using `java.util.Date`? `java.time.LocalDateTime`? joda time? – azurefrog Mar 10 '16 at 21:59
  • @azurefrog I am using java.util.Date and using SimpleDateFormater to format it. – Fable Mar 10 '16 at 22:00
  • See http://stackoverflow.com/questions/1555262/calculating-the-difference-between-two-java-date-instances – azurefrog Mar 10 '16 at 22:02
  • How exactly is `1 hour, 44 minutes and 56 seconds` different from `total hours, total minutes and total seconds`? – Jim Garrison Mar 10 '16 at 22:02
  • @JimGarrison Because instead of the total seconds being every second between the start and end date, i need it to be the number of seconds left of the current minute. – Fable Mar 10 '16 at 22:04

1 Answers1

1

You haven't specify your date format. Supposed you use the Date class, the following code gives you a difference in milliseconds.

long difference = dateEnd.getTime() - dateNow.getTime();

Then you approach to your result with a simple calculation:

int seconds = (int) (difference / 1000) % 60 ;
int minutes = (int) ((difference / (1000*60)) % 60);
int hours   = (int) ((difference / (1000*60*60)) % 24);
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183