w3resource

Java: Date before and after 1 year compare to current date


17. Date Before and After Year

Write a Java program to get a date before and after 1 year and compare it to the current date.

Sample Solution:

Java Code:

import java.util.*;
public class Exercise17 {
   public static void main(String[] args)
    {
      Calendar cal = Calendar.getInstance();
      Date cdate = cal.getTime();
      // get next year
      cal.add(Calendar.YEAR, 1); 
      Date nyear = cal.getTime();
      //get previous year
      cal.add(Calendar.YEAR, -2); 
      Date pyear = cal.getTime();
      System.out.println("\nCurrent Date : " + cdate);
      System.out.println("\nDate before 1 year : " + pyear);
      System.out.println("\nDate after 1 year  : " + nyear+"\n");  	
    }
}

Sample Output:

Current Date : Tue Jun 20 17:21:52 IST 2017
                              
Date before 1 year : Mon Jun 20 17:21:52 IST 2016 
                                                                                         
Date after 1 year  : Wed Jun 20 17:21:52 IST 2018

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

Pictorial Presentation:

Java Exercises: Java DateTime, Calendar Exercises - Date before and after 1 year compare to current date


Flowchart:

Flowchart: Java DateTime, Calendar Exercises - Date before and after 1 year compare to current date


For more Practice: Solve these Related Problems:

  • Write a Java program to calculate the date exactly one year before and one year after the current date.
  • Write a Java program to compare a date one year from now with today to check if they fall on the same day of the week.
  • Write a Java program to display the dates one year ago and one year later and compute the difference in days.
  • Write a Java program to determine the dates shifted by one year in both directions and compare them with today.

Go to:


PREV : Date After Two Weeks.
NEXT : Check Leap Year.

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.