Java Period – Difference between Dates in Days, Months and Years
Learn to create and use the Period class that was introduced as part of the new Date Time API in Java 8. The Period class represents the period of time in date-based values such as days, months, years, weeks, or years in the ISO-8601 calendar system such as “1 year and 2 months”.
The supported units of a period are YEARS , MONTHS and DAYS . All three fields are always present but may be set to zero or even a negative value.
For example, we can use the instance of Period to represent the total time spent by the student to complete the university degree.
The Period class is used to represent an amount of time using date-based values in the ISO-8601 period formats PnYnMnD and PnW .
For example, the P20Y2M25D string represents 20 years, 2 months, and 25 days.
The period of time can be obtained in the following ways.
1.1. Period between Two Dates
Mostly Period is used to represent a period of time between two dates (e.g. between two LocalDate instances).
LocalDate startLocalDate = LocalDate.of(2020, 3, 12); LocalDate endLocalDate = LocalDate.of(2020, 7, 20); Period periodBetween = Period.between(startLocalDate, endLocalDate); System.out.println(periodBetween); // P4M8D - 4 months and 8 days System.out.println(periodBetween.getDays()); //8 System.out.println(periodBetween.getMonths()); //4 System.out.println(periodBetween.getYears()); //0 System.out.println(periodBetween.get(ChronoUnit.DAYS)); //8
1.2. Creating Period with Values
Period class following methods to represent a time period in different units:
- ofDays(int days) – period representing a number of days.
- ofMonths(int months) – period representing a number of months.
- ofWeeks(int weeks) – period representing a number of weeks.
- ofYears(int years) – period representing a number of years.
//20 years, 3 months and 20 days Period periodFromUnits = Period.of(20, 3, 20); Period fromDays = Period.ofDays(150); // 150 days Period fromMonths = Period.ofMonths(4); // 4 months Period fromYears = Period.ofYears(10); // 10 years Period fromWeeks = Period.ofWeeks(15); // 15 weeks
1.3. Parse String to Period
Period can be obtained from containing ISO-8601 period formats.
//20 years, 3 months and 20 days Period periodFromString1 = Period.parse("P20Y3M20D"); //365 Days Period periodFromString2 = Period.parse("P365D"); //52 Weeks Period periodFromString3 = Period.parse("P52W");
2. Extracting the values from Period
The period values can be obtained via getter methods:
- Period.getDays() – Gets the amount of days of this period.
- Period.getMonths() – Gets the amount of months of this period.
- Period.getYears() – Gets the amount of years of this period.
- Period.get(TemporalUnit unit) – Gets the value of the requested unit. Please note that supported units are YEARS, MONTHS and DAYS . All other units throw an UnsupportedTemporalTypeException .
LocalDate startLocalDate = LocalDate.of(2020, 3, 12); LocalDate endLocalDate = LocalDate.of(2020, 7, 20); Period periodBetween = Period.between(startLocalDate, endLocalDate); periodBetween.getDays(); //8 periodBetween.getMonths(); //4 periodBetween.getYears(); //0 periodBetween.get(ChronoUnit.DAYS); //8 //Throws UnsupportedTemporalTypeException periodBetween.get(ChronoUnit.WEEKS);
We can add or subtract the time or another period from the given Period instance.
Note that Period is an immutable class so each method, listed below, will return a new instance of Period with the modified value.
- plus(period) – Returns a copy of given period with the specified period added.
- plusYears() – Returns a copy of given period with the specified years added.
- plusMonths() – Returns a copy of given period with the specified months added.
- plusDays() – Returns a copy of given period with the specified days added.
- minus(period) – Returns a copy of given period with the specified period subtracted.
- minusYears() – Returns a copy of given period with the specified years subtracted.
- minusMonths() – Returns a copy of given period with the specified months subtracted.
- minusDays() – Returns a copy of given period with the specified days subtracted.
- multipliedBy(scalar) – Returns a new instance with each element in this period multiplied by the specified scalar.
Period period = Period.ofDays(5); Period periodDaysAdded = period.plus(5); Period periodPlus1Year = period.plusYears(1L);
Java Code to Calculate Years Between Two Dates | Java Programs
Java program to find years between two dates – The following java program has been written in along with algorithmic explanation, if you have any doubts regarding that just do leave a comment here.
Java Program Calculate Years Between Dates
System . out . println ( date [ 0 ] [ 2 ] + «-» + date [ 0 ] [ 1 ] + «-» + date [ 0 ] [ 0 ] + » to » + date [ 1 ] [ 2 ] + «-» + date [ 1 ] [ 1 ] + «-» + date [ 1 ] [ 0 ] ) ;
if ( ( year % 400 == 0 ) || ( year % 4 == 0 && year % 100 != 0 ) ) // check whether year is a leap year
To calculate the exact number of years in between two dates, we will require to store 2 dates in a 2-D array (date[2][3]).
When one dimension is for first date and second date while the other is to store the year, month and day of each date. Along with this, we’ll also have another 1-D array (m) which has the fixed value of number of days in each month.
We first take in values of our date by making use of Scanner class to read it at runtime from the console screen.
In date array, date[0] is the first date while date[1] is the second date. Also for a given date[i], date[i][0] is the year, date[i][1] is the month and date[i][2] is the day.
After reading the first date (date[0]), we check if the entered date is valid or not by calling check_valid_date() method and sending date[0] and array m as parameters.
So now, the execution goes to the check_valid_date() method.
Here, first we check if the entered year is greater than zero and then, if it is leap year by calling the leapyear() method.
A year is said to be a leap year if it is divisible by 4 but, if it is also divisible by 100 under that case, it should be divisible by 400. Only if these conditions satisfy, it can be called a leap year.
Years between two dates
This example will demonstrate how to find the number of years between two dates using Java 8 date time api and Joda time. We will set the start date to December 25, 2004 and the end date to January 1, 2006. Then we will find the number of years between the start date and end date which equates to 1 year.
Java 8 Date and Time API
This snippet will find the difference between two dates in years using java 8 Duration.between and ChronoUnit.YEARS. Both approaches will calculate the amount of time between two temporal objects in the form of years.
@Test public void years_between_two_dates_in_java_with_java8 () LocalDate startDate = LocalDate.of(2004, Month.DECEMBER, 25); LocalDate endDate = LocalDate.of(2006, Month.JANUARY, 1); long numberOfYears = ChronoUnit.YEARS.between(startDate, endDate); assertEquals(1, numberOfYears); // or long numberOfYears2 = Period.between(startDate, endDate).getYears(); assertEquals(1, numberOfYears2); >
Joda Time
Using joda, this snippet will calculate number of years between two dates using Years.yearsBetween.
@Test public void years_between_two_dates_in_java_with_joda () DateTime start = new DateTime(2004, 12, 25, 0, 0, 0, 0); DateTime end = new DateTime(2006, 1, 1, 0, 0, 0, 0); Years years = Years.yearsBetween(start, end); int numberOfYears = years.getYears(); assertEquals(1, numberOfYears); >
Years between two dates posted by Justin Musgrove on 07 February 2014
Tagged: java, java-date, and java-date-between
Java – Difference Between Two Dates
In this Java tutorial, we will look at the programs to find the difference between two dates in Java.
The initial programs use the new Java 8 date-time API. In the last program, we will learn to find the difference using Jodatime API which was available even before Java 8 release. If you are still not using Java 8, then JodaTime should be your first choice.
1. Date Difference using Java 8 APIs
Legacy Java classes have always been lacking enough support to express dates and time periods in an effective way. Java 8 made the first attempt to upgrade this date/time API.
1.1. ChronoUnit.between() for Difference in All Time Units
The ChronoUnit instance represents a standard set of date periods units. We can use its different types of instances to find the difference in specific time measures.
LocalDate dateOfBirth = LocalDate.of(1980, Month.JULY, 4); LocalDate currentDate = LocalDate.now(); long diffInDays = ChronoUnit.DAYS.between(dateOfBirth, currentDate); long diffInMonths = ChronoUnit.MONTHS.between(dateOfBirth, currentDate); long diffInYears = ChronoUnit.YEARS.between(dateOfBirth, currentDate);
We can use ChronoUnit to know the difference in smaller time units e.g. milliseconds, minutes etc. But in that case, we will have to use LocalDateTime in place of LocalDate , because LocalDate does not have any time information associated with it.
LocalDateTime dateTime = LocalDateTime.of(1988, 7, 4, 0, 0); LocalDateTime dateTime2 = LocalDateTime.now(); long diffInNano = ChronoUnit.NANOS.between(dateTime, dateTime2); long diffInSeconds = ChronoUnit.SECONDS.between(dateTime, dateTime2); long diffInMilli = ChronoUnit.MILLIS.between(dateTime, dateTime2); long diffInMinutes = ChronoUnit.MINUTES.between(dateTime, dateTime2); long diffInHours = ChronoUnit.HOURS.between(dateTime, dateTime2);
We can even use the instances of ZonedDateTime to know the difference when both dates are in different time zones.
1.2. Period.between() for Difference in Days, Months and Years
The between() method returns a Period consisting of the number of years, months, and days between two dates.
- Note that the start date is included, but the end date is excluded.
- The result of this method can be a negative period if the end is before the start.
As stated above, Period class represents the time difference in the format of “x years, y months and z days”. So, when we call its getDays() method, it returns only the “z days” part.
LocalDate endofCentury = LocalDate.of(2014, 01, 01); LocalDate now = LocalDate.now(); Period diff = Period.between(endofCentury, now); System.out.printf("Difference is %d years, %d months and %d days old", diff.getYears(), diff.getMonths(), diff.getDays());
2.3. Duration.between() for Difference in Hours, Minutes and Seconds
Duration represents time difference in a smaller time-based amount of time such as hours, minutes, seconds, nanoseconds etc.
LocalDateTime dateTime = LocalDateTime.of(1988, 7, 4, 0, 0); LocalDateTime dateTime2 = LocalDateTime.now(); int diffInNano = java.time.Duration.between(dateTime, dateTime2).getNano(); long diffInSeconds = java.time.Duration.between(dateTime, dateTime2).getSeconds(); long diffInMilli = java.time.Duration.between(dateTime, dateTime2).toMillis(); long diffInMinutes = java.time.Duration.between(dateTime, dateTime2).toMinutes(); long diffInHours = java.time.Duration.between(dateTime, dateTime2).toHours();
Above all 3 programs have enough readability as well as the flexibility to know the difference between dates in multiple and different time units.