w3resource

Java: Get year and months between two dates


19. Get Year and Month Between Dates

Write a Java program to get the year and month between two dates.

Sample Solution:

Java Code:

import java.time.*;
public class Exercise19 {
   public static void main(String[] args)
    {
     LocalDate today = LocalDate.now();    
     LocalDate userday = LocalDate.of(2015, Month.MAY, 15); 
     Period diff = Period.between(userday, today); 
     System.out.println("\nDifference between "+ userday +" and "+ today +": " 
     + diff.getYears() +" Year(s) and "+ diff.getMonths() +" Month()s\n");
    }
}

Sample Output:

Difference between 2015-05-15 and 2017-06-20: 2 Year(s) and 1 Month()s

N.B.: The result may varry for your system date and time.

Pictorial Presentation:

Java Exercises: Java DateTime, Calendar Exercises - Get year and months between two dates.


Flowchart:

Flowchart: Java DateTime, Calendar Exercises - Get year and months between two dates


For more Practice: Solve these Related Problems:

  • Write a Java program to calculate the difference in years and months between two given dates.
  • Write a Java program to determine the number of complete months between two user-provided dates.
  • Write a Java program to compute the gap in years and remaining months between two dates.
  • Write a Java program to compare two dates and display the elapsed time in a "X years Y months" format.

Go to:


PREV : Check Leap Year.
NEXT : Get Current Timestamp.

Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.