How to Find Difference Between Two Joda-Time Datetimes in Minutes

How to find difference between two Joda-Time DateTimes in minutes

This will get you the difference between two DateTime objects in milliseconds:

DateTime d1 = new DateTime();
DateTime d2 = new DateTime();

long diffInMillis = d2.getMillis() - d1.getMillis();

Number of days between two dates in Joda-Time

Annoyingly, the withTimeAtStartOfDay answer is wrong, but only occasionally. You want:

Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays()

It turns out that "midnight/start of day" sometimes means 1am (daylight savings happen this way in some places), which Days.daysBetween doesn't handle properly.

// 5am on the 20th to 1pm on the 21st, October 2013, Brazil
DateTimeZone BRAZIL = DateTimeZone.forID("America/Sao_Paulo");
DateTime start = new DateTime(2013, 10, 20, 5, 0, 0, BRAZIL);
DateTime end = new DateTime(2013, 10, 21, 13, 0, 0, BRAZIL);
System.out.println(daysBetween(start.withTimeAtStartOfDay(),
end.withTimeAtStartOfDay()).getDays());
// prints 0
System.out.println(daysBetween(start.toLocalDate(),
end.toLocalDate()).getDays());
// prints 1

Going via a LocalDate sidesteps the whole issue.

Find the exact difference between two (Joda Time) DateTime objects in java

You are working too hard. You are using the wrong class for your purpose.

Period Class

In Joda-Time, use the Period class when you want to represent a span of time as a number of years, months, days, hours, minutes, seconds. Joda-Time represents a span of time in any of three ways: Interval, Duration, or Period.

Joda-Time follows the ISO 8601 standard for parsing and generating string representations of the date-time values. For Period that means the PnYnMnDTnHnMnS format where P marks the beginning while the T separates the year-month-day portion from the hour-minute-second portion. A half-hour is PT30M. P3Y6M4DT12H30M5S represents "three years, six months, four days, twelve hours, thirty minutes, and five seconds". Search StackOverflow.com for more info and examples.

Look at the PeriodFormatter and PeriodFormatterBuilder classes if you want to pretty-print with words.

You can also ask the Period object for the various component numbers if you need the integers.

Time Zone

Also, you should specify a time zone. If omitted then your JVM’s current default time zone is applied implicitly. Better to specify explicitly the time zone you desire/expect.

Always use proper time zone names, never the 3-4 letter codes. Those codes are neither standardized nor unique. And they further confuse the issue of Daylight Saving Time (DST).

Furthermore, commonly servers are kept on UTC time zone. Usually best to do nearly all of your business logic, data storage, data exchange, and logging in UTC.

Example Code

Note that you can ask DateTime for current moment without involving a java.util.Date object (as seen in your Question).

Example code for Period.

DateTimeZone zone = DateTimeZone.forID( "America/Detroit" ) ;
DateTime then = new DateTime( yourJUDate , zone ) ;
DateTime now = DateTime.now( zone ) ;
Period period = new Period( then , now ) ;

Difference between two DateTime objects in minutes

LocalDateTime fromdate = LocalDateTime.of(orderYear,orderMonth,orderDay,orderHour,orderMinute,orderSeconds);
LocalDateTime todate = LocalDateTime.of(deliverYear, deliverMonth, deliverDay,deliverHour,deliverMinute,deliverSeconds);
Duration difference = Duration.between(fromdate, todate);


Then you can format it using something similar to...

long hours = difference.toHours();
long mins = difference.minusHours(hours).toMinutes();

// Or if you're lucky enough to be using Java 9+
//String formatted = String.format("%dhrs %02dmins", duration.toHours(), duration.toMinutesPart());
String formatted = String.format("%dhrs %02dmins", hours, mins);


And just to prove the point...

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class Test {

public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
List<LocalDateTime> from = new ArrayList<>(5);
List<LocalDateTime> to = new ArrayList<>(5);

from.add(LocalDateTime.parse("2018-06-16 02:00:00", formatter));
from.add(LocalDateTime.parse("2018-06-16 03:00:00", formatter));
from.add(LocalDateTime.parse("2018-06-16 04:00:00", formatter));
from.add(LocalDateTime.parse("2018-06-16 05:00:00", formatter));
from.add(LocalDateTime.parse("2018-06-16 06:00:00", formatter));

to.add(LocalDateTime.parse("2018-06-18 02:00:00", formatter));
to.add(LocalDateTime.parse("2018-06-18 03:00:00", formatter));
to.add(LocalDateTime.parse("2018-06-18 04:00:00", formatter));
to.add(LocalDateTime.parse("2018-06-18 05:00:00", formatter));
to.add(LocalDateTime.parse("2018-06-18 06:00:00", formatter));

for (int index = 0; index < from.size(); index++) {
LocalDateTime fromDate = from.get(index);
LocalDateTime toDate = to.get(index);
String difference = formatDurationBetween(fromDate, toDate);
System.out.println(fromDate.format(formatter) + " - " + toDate.format(formatter) + " = " + difference);
}
}

public static String formatDurationBetween(LocalDateTime from, LocalDateTime to) {
Duration difference = Duration.between(from, to);

long days = difference.toDays();
difference = difference.minusDays(days);
long hours = difference.toHours();
long mins = difference.minusHours(hours).toMinutes();

return String.format("%dd %dh %02dm", days, hours, mins);
}

}


Outputs...

2018-06-16 02:00:00 - 2018-06-18 02:00:00 = 2d 0h 00m
2018-06-16 03:00:00 - 2018-06-18 03:00:00 = 2d 0h 00m
2018-06-16 04:00:00 - 2018-06-18 04:00:00 = 2d 0h 00m
2018-06-16 05:00:00 - 2018-06-18 05:00:00 = 2d 0h 00m
2018-06-16 06:00:00 - 2018-06-18 06:00:00 = 2d 0h 00m


You can of course make your own formatting algorithm based on your needs

Trying to find time difference in Joda Time between 2 DateTime objects

You are using the method withZone() which is defined to preserve the (POSIX) instant in milliseconds since 1970-01-01T00:00Z. So dtFrom and dtTo have still the same instant meaning they describe the same global time although their local time representations are different due to different time zones.

Result: The difference between two same instants is exactly equal to zero regardless which time unit you use.

However, if you are interested into the local time difference instead please determine the zone offset difference, for example using the method getOffset().

Joda time calculating the days, hours, minutes, and seconds between two datetime objects

toString() method in Period gives you the value as ISO8601 duration format.

From the API:

Gets the value as a String in the style of the ISO8601 duration
format. Technically, the output can breach the ISO specification as
weeks may be included. For example, "PT6H3M5S" represents 6 hours, 3
minutes, 5 seconds.

As you ask to get separately the days,hours,minutes and seconds you can use the convenient get methods from the API:

import org.joda.time.DateTime;
import org.joda.time.Period;

...
DateTime dt1 = new DateTime("2004-12-13T21:39:45.618-06:00");
DateTime dt2 = new DateTime("2004-12-13T21:39:45.618-08:00");
Period p = new Period(dt1, dt2);

System.out.println("DAYS: " + p.getDays())
System.out.println("HOURS: " + p.getHours());
System.out.println("MINUTES: " + p.getMinutes());
System.out.println("SECONDS: " + p.getSeconds());

Or alternatively as other answers suggests use PeriodFormatter.

How to calculate difference between two dates in years...etc with Joda-Time

Period gives you this out of the box.

Period period = new Period(d1, d2);
System.out.print(period.getYears() + " years, ");
System.out.print(period.getMonths() + " months, ");
// ...

To prettify and get a little more control over the output, you can use a PeriodFormatterBuilder.

Difference Between Two Joda DateTime In Months and Left Over Days

Use a org.joda.time.Period:

// fields used by the period - use only months and days
PeriodType fields = PeriodType.forFields(new DurationFieldType[] {
DurationFieldType.months(), DurationFieldType.days()
});
Period period = new Period(dateOfBirth, endDate)
// normalize to months and days
.normalizedStandard(fields);

The normalization is needed because the period usually creates things like "1 month, 2 weeks and 3 days", and the normalization converts it to "1 month and 17 days". Using the specific DurationFieldType's above also makes it convert years to months automatically.

Then you can get the number of months and days:

int months = period.getMonths();
int days = period.getDays();

Another detail is that when using DateTime objects, the Period will also consider the time (hour, minute, secs) to know if a day has passed.

If you want to ignore the time and consider only the date (day, month and year), don't forget to convert them to LocalDate:

// convert DateTime to LocalDate, so time is ignored
Period period = new Period(dateOfBirth.toLocalDate(), endDate.toLocalDate())
// normalize to months and days
.normalizedStandard(fields);

Joda time find difference between Hours

try like this,

int diff_hrs = getDiffHours(date,new Date());// pass your date object as startDate and pass current date as your endDate

public int getDiffHours(Date startDate, Date endDate){

Interval interval = new Interval(startDate.getTime(), endDate.getTime());
Period period = interval.toPeriod();
return period.getHours();
}


Related Topics



Leave a reply



Submit