SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd”); //For declaring values in new date objects. use same date format when creating dates Date date1 = sdf. parse(“1995-02-23”); //date1 is February 23, 1995 Date date2 = sdf. parse(“2001-10-31”); //date2 is October 31, 2001 Date date3 = sdf. parse(“1995-02-23”); //date3 is February 23, 1995
date1. compareTo(date2); //date1 < date2, returns less than 0 date2. compareTo(date1); //date2 > date1, returns greater than 0 date1. compareTo(date3); //date1 = date3, so will print 0 to console
System. out. print(date1. before(date2)); //prints true System. out. print(date2. before(date2)); //prints false
System. out. print(date2. after(date1));//prints true System. out. print(date1. after(date2));//prints false
System. out. print(date1. equals(date3));//prints true System. out. print(date1. equals(date2));//prints false
Calendar cal1 = Calendar. getInstance(); //declares cal1 Calendar cal2 = Calendar. getInstance(); //declares cal2 Calendar cal3 = Calendar. getInstance(); //declares cal3 cal1. setTime(date1); //applies date to cal1 cal2. setTime(date2); cal3. setTime(date3);
System. out. print(cal1. before(cal2)); //will print true
System. out. print(cal1. after(cal2)); //prints false
System. out. println(cal1. equals(cal3)); //prints true: cal1 == cal3 System. out. print(cal1. equals(cal2)); //prints false: cal1 != cal2
long time1 = getTime(date1); //declares primitive time1 from date1 long time2 = getTime(date2); //declares primitive time2 from date2
if(time1 < time2){ System. out. println(“date1 is before date2”); //will print since time1 <time2 } else{ System. out. println(“date1 is not before date2”); }
if(time2 > time1){ System. out. println(“date2 is after date1”); //will print since time2 > time1 } else{ System. out. println(“date2 is not after date1”); }
if(time1 == time2){ System. out. println(“the dates are equal”); } else{ System. out. println(“the dates are not equal”); //will print since time1 != time2 }