javadatetimeelapsedtimeelapsed

Converting elapsed milliseconds into proper java date format?


I stuck up in the middle of my development, I have requirement in such a way that i need to find the delay between two dates ie.. currentdate-date from database

and i need to display the delay in the format of dd:hh:mm . After referring lot of references i found how to convert to individual milliseconds hours and minutes , but what am expecting: if the result is some X milliseconds , i need to show it in proper day minute and seconds format

example : 2days:03minutes:46seconds

Here is the code am using :

Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
calendar1.setTime(date);
calendar2.setTime(date1);
long milliseconds1 = calendar1.getTimeInMillis();
long milliseconds2 = calendar2.getTimeInMillis();
long diff = milliseconds1 - milliseconds2;
System.out.println("diff ::"+diff);
long diffSeconds = diff / 1000;
long diffMinutes = diff / (60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
long diffDays = diff / (24 * 60 * 60 * 1000);

can anyone please suggest me what to do further? Please guide me ..


Solution

  • You need to first compute diffDays

    diffDays = diff / (24 * 60 * 60 * 1000);
    

    Then compute the remaining milliseconds:

    diff -= diffDays * 24 * 60 * 60 * 1000;
    

    Use the new diff to compute the diffHours and so on...

    A suggestions: use constant values like this:

    private static final int SECOND = 1000;
    private static final int MINUTE = 60 * SECOND;
    // and so on