Calender.before(), Calender.after() and Calender.equals()
Compare two Date dates using java.util.Calendar
<code>@Test<br>void testDateCompare3( ) throws ParseException {<br> SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");<br> Date date1 = sdf.parse("2009-12-31");<br> Date date2 = sdf.parse("2019-01-31");<br><br> System.out.println("date1 : " + sdf.format(date1));<br> System.out.println("date2 : " + sdf.format(date2));<br><br> Calendar cal1 = Calendar.getInstance();<br> Calendar cal2 = Calendar.getInstance();<br> cal1.setTime(date1);<br> cal2.setTime(date2);<br><br> if (cal1.after(cal2)) {<br> System.out.println("Date1 时间在 Date2 之后");<br> }<br><br> if (cal1.before(cal2)) {<br> System.out.println("Date1 时间在 Date2 之前");<br> }<br><br> if (cal1.equals(cal2)) {<br> System.out.println("Date1 时间与 Date2 相等");<br> }<br>}<br></code>
Output results:
<code>date1 : 2009-12-31<br>date2 : 2019-01-31<br>Date1 时间在 Date2 之前</code>
The above is the detailed content of How to use the before(), after() and equals() methods of the Calendar class in Java?. For more information, please follow other related articles on the PHP Chinese website!