How to Calculate Next Date and Year in Java | LocalDate and MonthDay Example Tutorial

Hello guys, if you are wondering how to calculate the next premium date, next birthday, or exact date for the next Christmas holiday in Java then you have come to the right place. Earlier, I have shared 20+ examples of Date and Time in Java, and in this article, I will show you how you can use the LocalDate and MonthDay class from the new Java 8 Date and Time package to calculate the next or previous date in Java. This new API is very well structured and you have classes to represent different Date concepts, for example, you can use LocalDate to represent a Date without time components like the next premium date or employee joining date or birth date. 

Similarly, you can use MonthDay class to represent a Month with a Day. These two classes are very useful while calculating the next or previous date for a particular event in Java. 


How to calculate the next Date in Java? 

here is an example of how to calculate the next date in Java, like the next birth date, next Christmas day, or next premium date. You can use LocalDate and MondayDay class from java.time package to perform simple Date arithmetic in Java. 

The code is self-explanatory, so I won't elaborate on it in detail, but you should notice the use of LocalDate, which is a date without a time or a timezone, as well as the MonthDay class, that just represents a month with a day. 

How to Calculate Next Date and Year in Java | LocalDate and MonthDay Example Tutorial


Btw, if you have any doubt in understanding any concept or any part of the code then feel free to drop a note and I'll try to explain. If you think an explanation is needed, tell us and I may update the article as well.

Java Program to calculate Next Date and Year Between Dates
package test;
 
import java.time.LocalDate;
import java.time.MonthDay;
import java.time.temporal.ChronoUnit;
import java.util.Scanner;
 
 
public class Test {
 
    public static void main(String[] args) {
        Scanner sysin = new Scanner(System.in);
        System.out.println("Please enter your first premium date,
            in year, month and day");

        int year = sysin.nextInt();
        int month = sysin.nextInt();
        int day = sysin.nextInt();

        LocalDate premiumStartDate = LocalDate.of(year, month, day);
        System.out.printf("Your first premium date was %s %n",
                                      premiumStartDate);
        System.out.printf("You have been paying premium from last %s years %n",
                                      getPaidYears(premiumStartDate));
 
        MonthDay primiumDay = MonthDay.from(premiumStartDate);
        System.out.printf("Your next premium is due on %s %n", 
                                      getNextPremiumDate(primiumDay)) ;
    }
 
    /**
     * Calculate number of years from the first premium paid
     * good example of how to find days, month and year
     * between two dates in Java.
     * @param issueDate
     * @return number of years from first payment
     */
    private static long getPaidYears(LocalDate issueDate) {
        return ChronoUnit.YEARS.between(issueDate, LocalDate.now());
    }
 
    /**
     * Calculate Next premium date, return this years date if premium day
     * is today or after today, otherwise next years date
     * @param premiumDay
     * @return  next premium date
     */
    private static LocalDate getNextPremiumDate(MonthDay premiumDay) {
        LocalDate today = LocalDate.now();
        LocalDate nextPremiumDay = premiumDay.atYear(today.getYear());
        if(nextPremiumDay.isAfter(today) || nextPremiumDay.equals(today))
            return nextPremiumDay;
        return nextPremiumDay.plusYears(1);
    }
}
 
 
Output
Please enter your first premium date, in year, month and day
2010
02
15
Your first premium date was 2010-02-15
You have been paying premium from last 4 years
Your next premium is due on 2015-02-15
 
 
Please enter your first premium date, in year, month and day
2012
02
25
Your first premium date was 2012-02-25
You have been paying premium from last 2 years
Your next premium is due on 2014-02-25
 
Invalid value
2012
25
02
Exception in thread "main" java.time.DateTimeException:
 Invalid value for MonthOfYear (valid values 1 - 12): 25
  at java.time.temporal.ValueRange.checkValidValue(ValueRange.java:309)
  at java.time.temporal.ChronoField.checkValidValue(ChronoField.java:703)
  at java.time.LocalDate.of(LocalDate.java:259)


In this example, we are asking users to enter the first premium date for their insurance. We then used the Scanner class to read the user input from the console and read the date, month, and year parts separately. 

Once we got the date, Month, and Year, we have created a LocalDate instance to represent that particular Date and printed it on the console. That's the first premium date. After that, we have used ChronoUnit.YEARS.between(issueDate, LocalDate.now())to calculate the number of years we have been paying a premium.

This is nothing but the difference between the current date and the first premium date. You can use this code to calculate the difference between any two dates in Java. After that, we have created another method to calculate the next premium date. 

This method takes a MonthDay object and sees if the current date is before or after the given date, if it's before then it returns the next premium date in the same year, otherwise it returns the premium date in the next year. 


That's all about how to use Date and Time in Java 8. You should use LocalDate if you are dealing with just dates like Birthdays, holidays, or any other date like premium start date, and premium renewal date.

Other Java Date and Time Tutorials You May like:
  • How to compare two dates in Java? (tutorial)
  • How to convert java.util.Date to java.sql.Timestamp in JDBC? (tutorial)
  • How to convert Date to LocalDateTime in Java 8? (tutorial)
  • How to get the current Timestamp value in Java? (tutorial)
  • 10 Things Java Developer should learn (article)
  • How to convert String to LocalDateTime in Java 8? (example)
  • The Java Developer RoadMap (guide)
  • How to convert java.util.Date to java.sql.Date in JDBC? (tutorial)
  • How to convert String to LocalDateTime in Java 8 (tutorial)
  • How to become a better Java Programmer (article)
  • How to get the current date and time in Java 6? (tutorial)
  • How to parse String to Date using the JodaTime library? (example)

Thanks for reading this article so far. If you like this Java tutorial then please share it with your friends and colleagues. If you have any questions or feedback please drop a note.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.