Java 8: Difference between two LocalDateTime in multiple units
Unfortunately, there doesn't seem to be a period class that spans time as well, so you might have to do the calculations on your own.
Fortunately, the date and time classes have a lot of utility methods that simplify that to some degree. Here's a way to calculate the difference although not necessarily the fastest:
LocalDateTime fromDateTime = LocalDateTime.of(1984, 12, 16, 7, 45, 55);
LocalDateTime toDateTime = LocalDateTime.of(2014, 9, 10, 6, 40, 45);
LocalDateTime tempDateTime = LocalDateTime.from( fromDateTime );
long years = tempDateTime.until( toDateTime, ChronoUnit.YEARS );
tempDateTime = tempDateTime.plusYears( years );
long months = tempDateTime.until( toDateTime, ChronoUnit.MONTHS );
tempDateTime = tempDateTime.plusMonths( months );
long days = tempDateTime.until( toDateTime, ChronoUnit.DAYS );
tempDateTime = tempDateTime.plusDays( days );
long hours = tempDateTime.until( toDateTime, ChronoUnit.HOURS );
tempDateTime = tempDateTime.plusHours( hours );
long minutes = tempDateTime.until( toDateTime, ChronoUnit.MINUTES );
tempDateTime = tempDateTime.plusMinutes( minutes );
long seconds = tempDateTime.until( toDateTime, ChronoUnit.SECONDS );
System.out.println( years + " years " +
months + " months " +
days + " days " +
hours + " hours " +
minutes + " minutes " +
seconds + " seconds.");
//prints: 29 years 8 months 24 days 22 hours 54 minutes 50 seconds.
The basic idea is this: create a temporary start date and get the full years to the end. Then adjust that date by the number of years so that the start date is less then a year from the end. Repeat that for each time unit in descending order.
Finally a disclaimer: I didn't take different timezones into account (both dates should be in the same timezone) and I also didn't test/check how daylight saving time or other changes in a calendar (like the timezone changes in Samoa) affect this calculation. So use with care.
Get difference of seconds beetween two dateTime
int seconds = (int) ChronoUnit.SECONDS.between(now, midnight);
Storing difference between two LocalDateTime values
The correct way is to decompose the difference by time unit such as in this answer.
Another option would be to save the date difference in a period and the time difference in a duration but this may lead to negative units in some cases:
LocalDateTime now = LocalDateTime.now();
LocalDateTime before = now.minusMonths(1).minusDays(5).minusHours(2).minusMinutes(30);
Period p = Period.between(before.toLocalDate(), now.toLocalDate());
Duration d = Duration.between(before.toLocalTime(), now.toLocalTime());
System.out.println(p + " + " + d);
which outputs: P1M5D + PT2H30M
Corner cases: if before = now.minusMonths(1).plusDays(1).plusMinutes(30);
, the duration is minus 30 minutes. This can't easily be fixed because doing an intuitive:
if (d.isNegative()) {
p = p.minusDays(1);
d = d.plusDays(1);
}
Can return negative days in other cases.
Java: time difference in milliseconds using LocalDateTime and ChronoUnit
I think the last param there is actually nano seconds:
https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#of-int-java.time.Month-int-int-int-int-int-
Switching to a diff of nanos output 2 in my case:
LocalDateTime startDate = LocalDateTime.of(2017, 11, 22, 21, 30, 30, 250);
LocalDateTime endDate = LocalDateTime.of(2017, 11, 22, 21, 30, 30, 252);
long diff = ChronoUnit.NANOS.between(startDate, endDate);
System.out.println(diff);
Yields:
2
I think that since you are comparing millis, the diff is being rounded down.
Java Subtracting LocalDateTime foo from LocalDateTime Bar
Why do you not simply use directly LocalDateTime
as parameter type this way:
LocalDateTime start = new LocalDateTime(2016, 10, 4, 17, 45);
LocalDateTime end = LocalDateTime.now();
PeriodType ptype = PeriodType.yearMonthDayTime();
Period diff = new Period(start, end, ptype);
See also the API of Joda-Time. You don't need to cast to DateTime
.
Calculating the difference between two Java date instances
The JDK Date
API is horribly broken unfortunately. I recommend using Joda Time library.
Joda Time has a concept of time Interval:
Interval interval = new Interval(oldTime, new Instant());
EDIT: 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!)
If you only care about time comparisions, most Date
implementations (including the JDK one) implements Comparable
interface which allows you to use the Comparable.compareTo()
Calculate days between two Dates in Java 8
If you want logical calendar days, use DAYS.between()
method from java.time.temporal.ChronoUnit
:
LocalDate dateBefore;
LocalDate dateAfter;
long daysBetween = DAYS.between(dateBefore, dateAfter);
If you want literal 24 hour days, (a duration), you can use the Duration
class instead:
LocalDate today = LocalDate.now()
LocalDate yesterday = today.minusDays(1);
// Duration oneDay = Duration.between(today, yesterday); // throws an exception
Duration.between(today.atStartOfDay(), yesterday.atStartOfDay()).toDays() // another option
For more information, refer to this document.
Related Topics
Why Is Java's Simpledateformat Not Thread-Safe
Difference Between File.Separator and Slash in Paths
Sorting a Collection of Objects
When and How to Use a Threadlocal Variable
Add Image Thumbnails to a Layout in a Grid
Why Does a Java Method Reference with Return Type Match the Consumer Interface
Concurrent Modification Exception
Process.Waitfor() Never Returns
Difference Between Processbuilder and Runtime.Exec()
How to Convert Hashmap to JSON Object in Java
How to Find Files That Match a Wildcard String in Java
How to Import a Class from Default Package
Spring: @Component Versus @Bean
Look and Feel Is Not Updating in Swing Jtabbedpane
Intellij Inspection Gives "Cannot Resolve Symbol" But Still Compiles Code