You can use the LocalDate.between() method to find the number of days between two dates in Java. This method is full proof and takes care of date-time nuisances like leap year and daylight saving time. Before Java 8, it was really difficult to calculate the number of days between two dates in Java. Though old Date and Calendar API provides methods to compare two dates like equals(), before(), and after(), no method can tell the exact difference in days or months between two dates unless you are using the joda-time library. All that is over now. You can now do better date-time arithmetic using Java 8 Date and Time API.
1. Number of Days between Date Prior to Java 8
Here is how you can find out the number of days between two dates in Java before Java 8 release:Date now = new Date();
Calendar cal = new GregorianCalendar(2015, Calendar.AUGUST, 1);
Date august1st = cal.getTime();
long difference = august1st.getTime() - now.getTime();
long numberOfDays = TimeUnit.DAYS.convert(difference,
TimeUnit.MILLISECONDS);
long numberOfHours = TimeUnit.HOURS.convert(difference,
TimeUnit.MILLISECONDS);
System.out.println("Number of days between today and 1st August"
Problems :
1. works 99% of the time but fails strangely at summer boundaries.
2. Doesn't take care of leap years.
3. Doesn't consider daylight saving time changes.
2. Calculating Number of Days between Dates after Java 8
Here is a better and easier way to calculate the difference between two days or the number of days between days after the Java 8 release. In this example, we have used the between()method to find the difference
You can also use the until() method of LocalDate to find a number of days between dates like how many days to Christmas or New Year. Though the end date is exclusive
LocalDate released = LocalDate.of(2014, Month.MARCH, 3);
LocalDate today = LocalDate.now();
long daysSinceJava8Released = ChronoUnit.DAYS.between(released, today);
System.out.println("Number of days since Java 8 released : "
+ daysSinceJava8Released);
Here is an example of LocalDate.until() method:
LocalDate firstAugust = LocalDate.of(2015, Month.AUGUST, 1);
long daysBetween = today.until(firstAugust, ChronoUnit.DAYS);
System.out.println("Today : " + today);
System.out.println("Days between today and 1st August 2015
using LocalDate.until(): "
+ daysBetween);
Benefits :
1. handles leap year, a number of days will be one more in leap year due to Feb being 29 days.
2. Handles daylight saving time
3. accurate and robust.
By the way, if you are new to Java then I also suggest you join a comprehensive Java course like The Complete Java Masterclass by Tim Buchalaka on Udemy to learn Java in a structured and organized manner. This 80-hour course is the most comprehensive and up-to-date and you can also buy it for just $10 on Udemy sales.
How to calculate the number of days between dates in Java 8
Here is our Java program to calculate the number of days between two dates in Java.import java.time.LocalDate; import java.time.Month; import java.time.temporal.ChronoUnit; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.concurrent.TimeUnit; /** * Java Program to calculate number of days between two dates in Java 8. * WE will also see how to do that in Java SE 6 and 7. * * @author WINDOWS 8 */ public class Java8Demo { public static void main(String args[]) throws InterruptedException{ // Prior to Java 8 - Number of days between two dates Date now = new Date(); Calendar cal = new GregorianCalendar(2015, Calendar.AUGUST, 1); Date august1st = cal.getTime(); long difference = august1st.getTime() - now.getTime(); long numberOfDays = TimeUnit.DAYS.convert(difference, TimeUnit.MILLISECONDS); long numberOfHours = TimeUnit.HOURS.convert(difference, TimeUnit.MILLISECONDS); System.out.println("Number of days between today and 1st August" + " using TimeUnit : " + numberOfDays); System.out.println("Number of hours between today and 1st August" + " using TimeUnit : " + numberOfHours); // In Java 8 - number of days between dates LocalDate released = LocalDate.of(2014, Month.MARCH, 3); LocalDate today = LocalDate.now(); long daysSinceJava8Released = ChronoUnit.DAYS.between(released, today); System.out.println("Number of days since Java 8 released : " + daysSinceJava8Released); // you can also use until() method of LocalDate to find // number of days between dates // how many days to 1st August 2015 // end date is exclusive though LocalDate firstAugust = LocalDate.of(2015, Month.AUGUST, 1); long daysBetween = today.until(firstAugust, ChronoUnit.DAYS); System.out.println("Today : " + today); System.out.println("Days between today and 1st August 2015 " + "using LocalDate.until(): " + daysBetween); // end date is exclusive long numOfDays = ChronoUnit.DAYS.between(today, firstAugust); System.out.println("Days between today and 1st August 2015 " + "using ChronoUnit : " + numOfDays); } } Output : Number of days between today and 1st August using TimeUnit : 1 Number of hours between today and 1st August using TimeUnit : 47 Number of days since Java 8 released : 514 Today : 2015-07-30 Days between today and 1st August 2015 using LocalDate.until(): 2 Days between today and 1st August 2015 using ChronoUnit : 2
Period vs Duration in Java
There are two classes in Java 8, Period and Duration, which you can use to calculate the difference between dates, but there is a catch. Difference between two time Instant is Duration, its very much same as how Dates are compared prior to Java 8 like endDate.getTime() - startDate.getTime().On the other hand, the difference between the two LocalDate is Period, which shows several elapsed days, months, and years between two dates. This is why until() method of LocalDate class return Period and not duration.
That's all about how to find a number of days between two dates in Java. Java 8 has everything you need to do with date and time, without hacking your way, like getting milliseconds and dividing it by some number to get days, months, or other time units. Also remember to use Period instead of Duration while getting the number of days between two dates, because Duration will not return correct values for leap years, but Period will do.
That's all about how to find a number of days between two dates in Java. Java 8 has everything you need to do with date and time, without hacking your way, like getting milliseconds and dividing it by some number to get days, months, or other time units. Also remember to use Period instead of Duration while getting the number of days between two dates, because Duration will not return correct values for leap years, but Period will do.
Other Java date and time tutorials you may like to explore
- 20 Essential Examples of Date and Time API of Java 8? (tutorial)
- How to get the current Timestamp value in Java? (tutorial)
- How to convert String to LocalDateTime in Java 8? (example)
- How to convert java.util.Date to java.sql.Timestamp in JDBC? (tutorial)
- How to parse String to Date using the JodaTime library? (example)
- How to get the current date and time in Java 6? (tutorial)
- How to compare two dates in Java? (tutorial)
- How to parse String to LocalDateTime in Java 8? (tutorial)
- How to convert Date to LocalDateTime in Java 8? (tutorial)
- How to convert java.util.Date to java.sql.Date in JDBC? (tutorial)
- Difference between java.sql.Time, java.sql.Timestamp, and java.sql.Date in JDBC? (answer)
Thanks for reading this article so far. If you find this LocalDate.between() and LocalDate.until() example in finding a number of days between dates useful then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.
P. S. - If you are new to Java world and looking for free training courses to learn Java from scratch then you can also check out this Java Tutorial for Complete Beginners(FREE) course on Udemy. It's completely free and more than 1.2 million people have joined this course to learn Java online.
No comments:
Post a Comment