I know there are lots of questions on SO about how to get Date
s in Java, but I want an example using new Java 8 Date
API. I also know about the JodaTime library, but I want a method without relying on external libraries.
The function needs to be compliant with these restrictions:
Date
objects (without time, I know about LocalDateTime
, but I need to do this with Date
instances)In Java 8, we can use ChronoUnit. DAYS. between(from, to) to calculate days between two dates.
LocalDate getDayOfWeek() method in Java The getDayOfWeek() method of LocalDate class in Java gets the day-of-week field, which is an enum DayOfWeek. Parameter: This method does not accepts any parameter. Return Value: The function returns the day of the week and not null.
getTime() – d1. getTime(). Use date-time mathematical formula to find the difference between two dates. It returns the years, days, hours, minutes, and seconds between the two specifies dates.
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.
Based on VGR's comments here is what you can use:
ChronoUnit.DAYS.between(firstDate, secondDate)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With