Home > Java > javaTutorial > body text

How to use the before(), after() and equals() methods of the Calendar class in Java?

王林
Release: 2023-05-07 09:19:08
forward
1932 people have browsed it

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>
Copy after login

Output results:

<code>date1 : 2009-12-31<br>date2 : 2019-01-31<br>Date1 时间在 Date2 之前</code>
Copy after login

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!

source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template