Pregunta

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 ..

¿Fue útil?

Solución 2

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

Otros consejos

Use Joda Time. The Java API doesn't contain anything dealing with "the difference between two date/time values". In Joda Time you can choose between Period (which is really for a calendar-centric difference) and a Duration (which is really just an elapsed time difference).

Ideally, use Joda Time for all your date/time concerns - it's a much, more better API.

In this case, I suspect you've logically got a Duration, but you'll want to convert it into a Period in order to use a PeriodFormatter for string conversions.

- I would recommend using the Joda Library when you deal with any date-time issues.

Joda Time has a concept of time Interval:

Interval interval = new Interval(oldTime, new Instant());

By the way, Joda has two concepts: Interval for representing an interval of time between two time instants (represent time between 8am and 10am), and a Duration that represents a length of time without the actual time boundaries (e.g. represent two hours!)

With JodaTime this is really easy. See the following code:

public void testJoda() {
    DateTime then = new DateTime("2012-03-23T02:30:00.000");
    DateTime now = new DateTime("2012-03-24T02:29:00.000");

    DurationFieldType[] ddhhmm = { DurationFieldType.days(),
            DurationFieldType.hours(), DurationFieldType.minutes() };
    Period p = new Period(then, now, PeriodType.forFields(ddhhmm));
    System.out.println(p.toString());

    p = new Period(then, now, PeriodType.days());
    System.out.println(p.toString());

    p = new Period(then, now, PeriodType.hours());
    System.out.println(p.toString());

    DurationFieldType[] hhmm  = { DurationFieldType.hours(), DurationFieldType.minutes() };
    p = new Period(then, now, PeriodType.forFields(hhmm));
    System.out.println(p.toString());
}

which tests for an interval of 23h59m. Its output is as expected:

PT23H59M
P0D
PT23H
PT23H59M

Take the same interval, one day later, just around the spring DST jump on March 25th:

DateTime then = new DateTime("2012-03-24T02:30:00.000");
DateTime now = new DateTime("2012-03-25T03:29:00.000");

and you correctly get:

P1DT-1M
P1D
PT23H
PT23H59M

It doesn't get much easier than that, really.

Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
calendar1.setTime(date);
calendar2.setTime(date1);

int dayDiff = calendar1.get(Calendar.DAY_OF_MONTH) - calendar2.get(Calendar.DAY_OF_MONTH);  
int hourDiff = calendar1.get(Calendar.HOUR_OF_DAY) -calendar2.get(Calendar.HOUR_OF_DAY);   
int dayDiff = calendar1.get(Calendar.SECOND) - calendar2.get(Calendar.SECOND);

tl;dr

Duration.between(   // Represent a span of time, unattached to the timeline.
    earlier ,       // `Instant` class represents a moment in UTC with a resolution as fine as nanoseconds. Current moment captured in microseconds, depending on capability of host computer hardware and operating system.
    Instant.now()
)                   // Returns a `Duration` object. Call `to…Part` methods to get the days, hours, minutes, seconds as separate numbers.

java.time

So much easier when using the modern java.time classes that supplanted the troublesome old date-time classes bundled with the earliest versions of Java.

Get the current moment in UTC. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

The current moment is captured in milliseconds in Java 8 specifically. In Java 9 and later, you may see the current moment captured with a finer granularity due to a fresh implementation of Clock. In Oracle Java 9 JDK on macOS Sierra, I get the current moment in microseconds (six digits of decimal fraction second).

Instant earlier = Instant.now() ;
…
Instant later = Instant.now() ;

Calculate elapsed time as a span-of-time unattached to the timeline. For a scale of hours-minutes-seconds (and days as 24-hour chunks of time unrelated to calendar), use Duration. For a scale of years-months-days, use Period.

Duration d = Duration.between( earlier , later ) ;

Generate a String is standard ISO 8601 format, PnYnMnDTnHnMnS, where the P marks the beginning and the T separates the years-months-days from the hours-minutes-seconds.

String output = d.toString() ;  // Standard ISO 8601 format.

I strongly recommend using the standard formats rather than the format seen in the Question. I have seen the time-of-day format cause so much confusion and ambiguity where it can be mistaken for, well, a time-of-day rather than a span-of-time. The ISO 8601 formats were wisely designed to avoid such ambiguities. But if you insist, in Java 9 and later you may ask for the parts of a Duration by calling the to…Part methods.

long days = d.toDaysPart() ;  // 24-hour chunks of time, unrelated to calendar dates.
int hours = d.toHoursPart() ;
int minutes = d.toMinutesPart() ;

Then assemble as you desire into a string.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top