Sunday, October 28, 2018

How to check date older than an year? [in Java]

The following java program will check for a date older than 365 days.

 public class CheckDateOlderThan365Days {

 public static void main(String[] args) {
  String givenDateStr = "12/20/2014";
  Date givenDate = new Date(givenDateStr);
  
  Date oldDate = new Date();
  Calendar cal = new GregorianCalendar();
  cal.setTime(oldDate);
  cal.add(Calendar.DAY_OF_MONTH, -365);
  oldDate = cal.getTime();
  
  boolean isDateOlder = givenDate.before(oldDate);
  if(isDateOlder){
   System.out.printf("Given date %s is older than 365 days",givenDate);
  } else {
   System.out.printf("Given date %s is newer than 365 days",givenDate);
  }

 }

}
 
 Output:Given date Sat Dec 20 00:00:00 EST 2014 is older than 365 days
 

No comments:

Post a Comment