logo

Como comparar datas em Java

Em Java , enquanto tratamos data e tempo , às vezes precisamos comparar datas . O comparação de datas em Java não é o mesmo que a comparação de dois números. Então, é uma tarefa um pouco complicada compare duas datas em Java . Não precisamos implementar nenhuma lógica para comparar datas . Para facilitar esta tarefa Java fornece compareTo(), antes(), depois(), e é igual a() método. Nesta seção, vamos aprender como comparar duas datas em Java .

Existem quatro classes em Java que fornecem métodos para comparar duas datas.

  • Usando compareTo() Método
  • Usando Data Aula
  • Usando Calendário Aula
  • Usando DataLocal Aula

Usando o método Date.compareTo()

Classe de data Java fornece diferentes métodos relacionados a horas e datas. É uma aula dejava.utilpacote. A classe implementa as interfaces Serializable, Cloneable e Comparable.

Para comparação de duas datas, a classe fornece compareTo() método. Ele compara datas para pedidos. Ele analisa uma data (a ser comparada) como parâmetro. Isso joga Null Pointer Exception se a data do argumento for nula.

Sintaxe:

 public int compareTo(Date anotherDate) 

Ele retorna valores inteiros:

    0:se ambas as datas forem iguais.Um valor menor que 0:se a data for anterior à data do argumento.Um valor maior que 0:se a data for posterior à data do argumento.

Lembrar: Se você estiver lidando com data em Java, não esqueça de importar java.text.SimpleDateFormat, java.text.ParseException,java.util.Date.

Vamos implementar o método compareTo() e comparar duas datas.

No exemplo a seguir, criamos uma instância do SimpleDateFormat classe que nos permite usar diferentes formatos de data. Depois disso, pegamos duas variáveis data1 e data2 do tipo Data. Ao usar o analisar() método da classe SimpleDateFormat, analisamos as datas para comparar. O método retorna um data analisado a partir da string. Passamos as variáveis ​​date1 e date2 do tipo Date no formatar() método. O método fornece a string formatada de data/hora.

Para comparar as duas datas, usamos o compareTo() método. Se ambas as datas forem iguais ele imprime Ambas as datas são iguais. Se data1 é maior que data2 , ele imprime A data 1 vem depois da data 2 . Se data1 é menor que data2 , ele imprime A data 1 vem depois da data 2 .

CompareDatesExample1.java

 import java.util.Date; import java.text.SimpleDateFormat; import java.text.ParseException; public class CompareDatesExample1 { public static void main(String[] args) throws ParseException { //object of SimpleDateFormat class SimpleDateFormat sdf = new SimpleDateFormat(&apos;yyyy-MM-dd&apos;); //dates to be compare Date date1 = sdf.parse(&apos;2020-07-20&apos;); Date date2 = sdf.parse(&apos;2020-06-18&apos;); //prints dates System.out.println(&apos;Date 1: &apos; + sdf.format(date1)); System.out.println(&apos;Date 2: &apos; + sdf.format(date2)); //comparing dates if(date1.compareTo(date2) &gt; 0) { System.out.println(&apos;Date 1 comes after Date 2&apos;); } else if(date1.compareTo(date2) <0) 1 { system.out.println('date comes before date 2'); } else if(date1.compareto(date2)="=" 0) system.out.println('both dates are equal'); < pre> <p> <strong>Output:</strong> </p> <pre> Date 1: 2020-07-20 Date 2: 2020-06-18 Date 1 comes after Date 2 </pre> <h2>Using Date Class</h2> <p>Java date class provides before() , after() , and equals() method to compare two dates.</p> <p> <strong>before():</strong> The method check that the date comes before the specified date or not. It parses a parameter of type Date. It returns <strong>true</strong> if and only if the instant of time represented by this Date object is strictly earlier than the instant represented by when, <strong>false</strong> otherwise.</p> <p> <strong>Syntax:</strong> </p> <pre> public boolean before(Date when) </pre> <p>It throws <strong>NullPointerException</strong> if when is null.</p> <p> <strong>after():</strong> The method check that the date comes after the specified date or not. It parses a parameter of type Date. It returns <strong>true</strong> if and only if the instant of time represented by this Date object is strictly later than the instant represented by when, <strong>false</strong> otherwise.</p> <p> <strong>Syntax:</strong> </p> <pre> public boolean after(Date when) </pre> <p>It throws <strong>NullPointerException</strong> if when is null.</p> <p> <strong>equals():</strong> The method checks (compare) the equality of two dates. It overrides the equals() method of the Object class. It returns true if the objects are same, else returns false. Therefore, the Date objects will be equal if and only if the getTime() method returns the same long value for both dates.</p> <p> <strong>Syntax:</strong> </p> <pre> public boolean equals (Object obj) </pre> <p>Let&apos;s use the above-explained method in an example and compare two dates with the help of these methods.</p> <p> <strong>CompareDatesExample2.java</strong> </p> <pre> import java.util.Date; import java.text.ParseException; import java.text.SimpleDateFormat; public class CompareDatesExample2 { public static void main(String args[]) throws ParseException { //Creating an object of the SimpleDateFormat class SimpleDateFormat sdfo = new SimpleDateFormat(&apos;yyyy-MM-dd&apos;); //dates to be compared Date date1 = sdfo.parse(&apos;2019-01-01&apos;); Date date2 = sdfo.parse(&apos;2020-01-01&apos;); // Print the dates System.out.println(&apos;Date1: &apos; + sdfo.format(date1)); System.out.println(&apos;Date2: &apos; + sdfo.format(date2)); //Compare the two dates if (date1.after(date2)) { //if date1&gt;date2, prints the following statement System.out.println(&apos;Date1 comes after Date2&apos;); } else if (date1.before(date2)) { //if date1<date2, prints the following statement system.out.println('date1 comes before date2'); } else if (date1.equals(date2)) { date1="date2" system.out.println('both dates are equal'); < pre> <p> <strong>Output:</strong> </p> <pre> Date1: 2019-01-01 Date2: 2020-01-01 Date1 comes before Date2 </pre> <h2>Using Calendar Class</h2> <p>Like the Java Date class, the <a href="/java-calendar-class"> <strong>Calendar</strong> class</a> also provides before() , after() , and equals() methods . All three methods have the same signature, as we have explained above.</p> <p>Let&apos;s use the Calendar class and compare two dates with the help of after(), before(), and equals() method.</p> <p>In the following example, we have used the same method used in the previous example, except the <strong>getInstance()</strong> and <strong>setTime()</strong> methods.</p> <p> <strong>getInstance():</strong> It is a static method of the Calendar. It returns a Calendar using the default time zone and locale.</p> <p> <strong>Syntax:</strong> </p> <pre> public static Calendar getInstance() </pre> <p> <strong>setTime():</strong> The method sets the calendar time according to the specified date. It parses a parameter of type Date.</p> <p> <strong>Syntax:</strong> </p> <pre> public final void setTime(Date date) </pre> <p> <strong>CompareDatesExample3.java</strong> </p> <pre> import java.util.Date; import java.util.Calendar; import java.text.ParseException; import java.text.SimpleDateFormat; public class CompareDatesExample3 { public static void main(String args[]) throws ParseException { // Create SimpleDateFormat object SimpleDateFormat sdf = new SimpleDateFormat(&apos;yyyy-MM-dd&apos;); //dates to be compare Date date1 = sdf.parse(&apos;2020-12-01&apos;); Date date2 = sdf.parse(&apos;2020-12-01&apos;); // Prints the dates System.out.println(&apos;Date1: &apos; + sdf.format(date1)); System.out.println(&apos;Date2: &apos; + sdf.format(date2)); //invoking getInstance() method Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); cal1.setTime(date1); cal2.setTime(date2); //compare two dates if (cal1.after(cal2)) { //if date1&gt;date2 System.out.println(&apos;Date1 comes after Date2&apos;); } else if (cal1.before(cal2)) { //if date1<date2 system.out.println('date1 comes before date2'); } else if (cal1.equals(cal2)) { date1="date2" system.out.println('both dates are equal'); < pre> <p> <strong>Output:</strong> </p> <pre> Date1: 2020-12-01 Date2: 2020-12-01 Both dates are equal </pre> <h2>Using LocalDate Class</h2> <p>Java provides another <strong>LocalDate</strong> class to compare two LocalDate, LocalTime, and LocalDateTime. It is the member of <span>java.time</span> package. The class provides isBefore(), isAfter(), isEquals(), and compareTo() method to compare dates. These methods works same as the method before(), after(), and equals() of the Date and Calendar class.</p> <p>Let&apos;s use the <a href="/java-localdate-class">LocalDate class</a> in an example to compare two dates.</p> <p>In the following example, we have used the following method to compare two dates. All the methods check the dates according to the local-time line.</p> <p> <strong>of():</strong> It is a static method of LocalDate class. It obtains an instance of LocalDate form year, month, and day. It accepts three parameters year, month, and date of type int. It returns a LocalDate with the specified date.</p> <p> <strong>Syntax:</strong> </p> <pre> public static LocalDate of(int year, int month, int dayOfMonth) </pre> <p>where:</p> <p> <strong>year:</strong> must be between MIN_YEAR to MAX_YEAR.</p> <p> <strong>month:</strong> must be between 1 (January) to 12 (December).</p> <p> <strong>datOfMonth:</strong> must be between 1 to 31.</p> <p>It throws DateTimeException if the value of any parameter is out of range.</p> <p> <strong>isBefore():</strong> The method checks the date is before the specified date. It parses a date (to compare) as a parameter. It returns true if and only if the date is before the specified date. Its comparison approach is different from <strong>compareTo(ChronoLocalDate).</strong> </p> <p> <strong>Syntax:</strong> </p> <pre> public boolean isBefore(ChronoLocalDate other) </pre> <p> <strong>isAfter():</strong> The method checks the date is before the specified date. It parses a date (to compare) as a parameter. It returns true if and only if the date is before the specified date. Its comparison approach is different from <strong>compareTo(ChronoLocalDate)</strong> .</p> <p> <strong>Syntax:</strong> </p> <pre> public boolean isAfter(ChronoLocalDate other) </pre> <p> <strong>isEqual():</strong> The method compares the dates are equal or not. If both dates are equal it returns true, false otherwise. It parses a date (to compare) as a parameter.</p> <p>It returns true if and only if the date is before the specified date. Its comparison approach is different from <strong>compareTo(ChronoLocalDate).</strong> </p> <p> <strong>Syntax:</strong> </p> <pre> public boolean isEqual(ChronoLocalDate other) </pre> <p> <strong>CompareDatesExample4.java</strong> </p> <pre> import java.time.LocalDate; public class CompareDatesExample4 { public static void main(String[] args) { // Create LocalDate objects with dates LocalDate date1 = LocalDate.of(2020,9,29); LocalDate date2 = LocalDate.of(2020,12,07); // Print the Dates System.out.println(&apos;Date1: &apos; + date1); System.out.println(&apos;Date2: &apos; + date2); //comparing two dates if (date1.isAfter(date2)) { System.out.println(&apos;Date1 comes after Date2&apos;); } else if (date1.isBefore(date2)) { System.out.println(&apos;Date1 comes before Date2&apos;); } else if (date1.isEqual(date2)) { System.out.println(&apos;Both dates are equal&apos;); } } } </pre> <p> <strong>Output:</strong> </p> <pre> Date1: 2020-09-29 Date2: 2020-12-07 Date1 comes before Date2 </pre> <hr></date2></pre></date2,></pre></0)>

Usando classe de data

A classe de data Java fornece os métodos before() , after() e equals() para comparar duas datas.

modelo de referência osi em redes

antes(): O método verifica se a data é anterior à data especificada ou não. Ele analisa um parâmetro do tipo Data. Ele retorna verdadeiro se e somente se o instante de tempo representado por este objeto Date for estritamente anterior ao instante representado por quando, falso de outra forma.

Sintaxe:

 public boolean before(Date when) 

Isso joga Null Pointer Exception se quando for nulo.

depois(): O método verifica se a data vem depois da data especificada ou não. Ele analisa um parâmetro do tipo Data. Ele retorna verdadeiro se e somente se o instante de tempo representado por este objeto Date for estritamente posterior ao instante representado por quando, falso de outra forma.

Sintaxe:

 public boolean after(Date when) 

Isso joga Null Pointer Exception se quando for nulo.

é igual a(): O método verifica (compara) a igualdade de duas datas. Ele substitui o método equals() da classe Object. Ele retorna verdadeiro se os objetos forem iguais, caso contrário, retorna falso. Portanto, os objetos Date serão iguais se e somente se o método getTime() retornar o mesmo valor longo para ambas as datas.

Sintaxe:

 public boolean equals (Object obj) 

Vamos usar o método explicado acima em um exemplo e comparar duas datas com a ajuda desses métodos.

comentários java

CompareDatesExample2.java

 import java.util.Date; import java.text.ParseException; import java.text.SimpleDateFormat; public class CompareDatesExample2 { public static void main(String args[]) throws ParseException { //Creating an object of the SimpleDateFormat class SimpleDateFormat sdfo = new SimpleDateFormat(&apos;yyyy-MM-dd&apos;); //dates to be compared Date date1 = sdfo.parse(&apos;2019-01-01&apos;); Date date2 = sdfo.parse(&apos;2020-01-01&apos;); // Print the dates System.out.println(&apos;Date1: &apos; + sdfo.format(date1)); System.out.println(&apos;Date2: &apos; + sdfo.format(date2)); //Compare the two dates if (date1.after(date2)) { //if date1&gt;date2, prints the following statement System.out.println(&apos;Date1 comes after Date2&apos;); } else if (date1.before(date2)) { //if date1<date2, prints the following statement system.out.println(\'date1 comes before date2\'); } else if (date1.equals(date2)) { date1="date2" system.out.println(\'both dates are equal\'); < pre> <p> <strong>Output:</strong> </p> <pre> Date1: 2019-01-01 Date2: 2020-01-01 Date1 comes before Date2 </pre> <h2>Using Calendar Class</h2> <p>Like the Java Date class, the <a href="/java-calendar-class"> <strong>Calendar</strong> class</a> also provides before() , after() , and equals() methods . All three methods have the same signature, as we have explained above.</p> <p>Let&apos;s use the Calendar class and compare two dates with the help of after(), before(), and equals() method.</p> <p>In the following example, we have used the same method used in the previous example, except the <strong>getInstance()</strong> and <strong>setTime()</strong> methods.</p> <p> <strong>getInstance():</strong> It is a static method of the Calendar. It returns a Calendar using the default time zone and locale.</p> <p> <strong>Syntax:</strong> </p> <pre> public static Calendar getInstance() </pre> <p> <strong>setTime():</strong> The method sets the calendar time according to the specified date. It parses a parameter of type Date.</p> <p> <strong>Syntax:</strong> </p> <pre> public final void setTime(Date date) </pre> <p> <strong>CompareDatesExample3.java</strong> </p> <pre> import java.util.Date; import java.util.Calendar; import java.text.ParseException; import java.text.SimpleDateFormat; public class CompareDatesExample3 { public static void main(String args[]) throws ParseException { // Create SimpleDateFormat object SimpleDateFormat sdf = new SimpleDateFormat(&apos;yyyy-MM-dd&apos;); //dates to be compare Date date1 = sdf.parse(&apos;2020-12-01&apos;); Date date2 = sdf.parse(&apos;2020-12-01&apos;); // Prints the dates System.out.println(&apos;Date1: &apos; + sdf.format(date1)); System.out.println(&apos;Date2: &apos; + sdf.format(date2)); //invoking getInstance() method Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); cal1.setTime(date1); cal2.setTime(date2); //compare two dates if (cal1.after(cal2)) { //if date1&gt;date2 System.out.println(&apos;Date1 comes after Date2&apos;); } else if (cal1.before(cal2)) { //if date1<date2 system.out.println(\'date1 comes before date2\'); } else if (cal1.equals(cal2)) { date1="date2" system.out.println(\'both dates are equal\'); < pre> <p> <strong>Output:</strong> </p> <pre> Date1: 2020-12-01 Date2: 2020-12-01 Both dates are equal </pre> <h2>Using LocalDate Class</h2> <p>Java provides another <strong>LocalDate</strong> class to compare two LocalDate, LocalTime, and LocalDateTime. It is the member of <span>java.time</span> package. The class provides isBefore(), isAfter(), isEquals(), and compareTo() method to compare dates. These methods works same as the method before(), after(), and equals() of the Date and Calendar class.</p> <p>Let&apos;s use the <a href="/java-localdate-class">LocalDate class</a> in an example to compare two dates.</p> <p>In the following example, we have used the following method to compare two dates. All the methods check the dates according to the local-time line.</p> <p> <strong>of():</strong> It is a static method of LocalDate class. It obtains an instance of LocalDate form year, month, and day. It accepts three parameters year, month, and date of type int. It returns a LocalDate with the specified date.</p> <p> <strong>Syntax:</strong> </p> <pre> public static LocalDate of(int year, int month, int dayOfMonth) </pre> <p>where:</p> <p> <strong>year:</strong> must be between MIN_YEAR to MAX_YEAR.</p> <p> <strong>month:</strong> must be between 1 (January) to 12 (December).</p> <p> <strong>datOfMonth:</strong> must be between 1 to 31.</p> <p>It throws DateTimeException if the value of any parameter is out of range.</p> <p> <strong>isBefore():</strong> The method checks the date is before the specified date. It parses a date (to compare) as a parameter. It returns true if and only if the date is before the specified date. Its comparison approach is different from <strong>compareTo(ChronoLocalDate).</strong> </p> <p> <strong>Syntax:</strong> </p> <pre> public boolean isBefore(ChronoLocalDate other) </pre> <p> <strong>isAfter():</strong> The method checks the date is before the specified date. It parses a date (to compare) as a parameter. It returns true if and only if the date is before the specified date. Its comparison approach is different from <strong>compareTo(ChronoLocalDate)</strong> .</p> <p> <strong>Syntax:</strong> </p> <pre> public boolean isAfter(ChronoLocalDate other) </pre> <p> <strong>isEqual():</strong> The method compares the dates are equal or not. If both dates are equal it returns true, false otherwise. It parses a date (to compare) as a parameter.</p> <p>It returns true if and only if the date is before the specified date. Its comparison approach is different from <strong>compareTo(ChronoLocalDate).</strong> </p> <p> <strong>Syntax:</strong> </p> <pre> public boolean isEqual(ChronoLocalDate other) </pre> <p> <strong>CompareDatesExample4.java</strong> </p> <pre> import java.time.LocalDate; public class CompareDatesExample4 { public static void main(String[] args) { // Create LocalDate objects with dates LocalDate date1 = LocalDate.of(2020,9,29); LocalDate date2 = LocalDate.of(2020,12,07); // Print the Dates System.out.println(&apos;Date1: &apos; + date1); System.out.println(&apos;Date2: &apos; + date2); //comparing two dates if (date1.isAfter(date2)) { System.out.println(&apos;Date1 comes after Date2&apos;); } else if (date1.isBefore(date2)) { System.out.println(&apos;Date1 comes before Date2&apos;); } else if (date1.isEqual(date2)) { System.out.println(&apos;Both dates are equal&apos;); } } } </pre> <p> <strong>Output:</strong> </p> <pre> Date1: 2020-09-29 Date2: 2020-12-07 Date1 comes before Date2 </pre> <hr></date2></pre></date2,>

Usando a classe Calendário

Assim como a classe Java Date, o Calendário aula também fornece métodos before() , after() e equals() . Todos os três métodos têm a mesma assinatura, conforme explicamos acima.

Vamos usar a classe Calendar e comparar duas datas com a ajuda dos métodos after(), before() e equals().

No exemplo a seguir, usamos o mesmo método usado no exemplo anterior, exceto o getInstance() e definir tempo() métodos.

getInstance(): É um método estático do Calendário. Ele retorna um calendário usando o fuso horário e a localidade padrão.

Sintaxe:

 public static Calendar getInstance() 

definir tempo(): O método define a hora do calendário de acordo com a data especificada. Ele analisa um parâmetro do tipo Data.

Sintaxe:

 public final void setTime(Date date) 

CompareDatesExample3.java

 import java.util.Date; import java.util.Calendar; import java.text.ParseException; import java.text.SimpleDateFormat; public class CompareDatesExample3 { public static void main(String args[]) throws ParseException { // Create SimpleDateFormat object SimpleDateFormat sdf = new SimpleDateFormat(&apos;yyyy-MM-dd&apos;); //dates to be compare Date date1 = sdf.parse(&apos;2020-12-01&apos;); Date date2 = sdf.parse(&apos;2020-12-01&apos;); // Prints the dates System.out.println(&apos;Date1: &apos; + sdf.format(date1)); System.out.println(&apos;Date2: &apos; + sdf.format(date2)); //invoking getInstance() method Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); cal1.setTime(date1); cal2.setTime(date2); //compare two dates if (cal1.after(cal2)) { //if date1&gt;date2 System.out.println(&apos;Date1 comes after Date2&apos;); } else if (cal1.before(cal2)) { //if date1<date2 system.out.println(\'date1 comes before date2\'); } else if (cal1.equals(cal2)) { date1="date2" system.out.println(\'both dates are equal\'); < pre> <p> <strong>Output:</strong> </p> <pre> Date1: 2020-12-01 Date2: 2020-12-01 Both dates are equal </pre> <h2>Using LocalDate Class</h2> <p>Java provides another <strong>LocalDate</strong> class to compare two LocalDate, LocalTime, and LocalDateTime. It is the member of <span>java.time</span> package. The class provides isBefore(), isAfter(), isEquals(), and compareTo() method to compare dates. These methods works same as the method before(), after(), and equals() of the Date and Calendar class.</p> <p>Let&apos;s use the <a href="/java-localdate-class">LocalDate class</a> in an example to compare two dates.</p> <p>In the following example, we have used the following method to compare two dates. All the methods check the dates according to the local-time line.</p> <p> <strong>of():</strong> It is a static method of LocalDate class. It obtains an instance of LocalDate form year, month, and day. It accepts three parameters year, month, and date of type int. It returns a LocalDate with the specified date.</p> <p> <strong>Syntax:</strong> </p> <pre> public static LocalDate of(int year, int month, int dayOfMonth) </pre> <p>where:</p> <p> <strong>year:</strong> must be between MIN_YEAR to MAX_YEAR.</p> <p> <strong>month:</strong> must be between 1 (January) to 12 (December).</p> <p> <strong>datOfMonth:</strong> must be between 1 to 31.</p> <p>It throws DateTimeException if the value of any parameter is out of range.</p> <p> <strong>isBefore():</strong> The method checks the date is before the specified date. It parses a date (to compare) as a parameter. It returns true if and only if the date is before the specified date. Its comparison approach is different from <strong>compareTo(ChronoLocalDate).</strong> </p> <p> <strong>Syntax:</strong> </p> <pre> public boolean isBefore(ChronoLocalDate other) </pre> <p> <strong>isAfter():</strong> The method checks the date is before the specified date. It parses a date (to compare) as a parameter. It returns true if and only if the date is before the specified date. Its comparison approach is different from <strong>compareTo(ChronoLocalDate)</strong> .</p> <p> <strong>Syntax:</strong> </p> <pre> public boolean isAfter(ChronoLocalDate other) </pre> <p> <strong>isEqual():</strong> The method compares the dates are equal or not. If both dates are equal it returns true, false otherwise. It parses a date (to compare) as a parameter.</p> <p>It returns true if and only if the date is before the specified date. Its comparison approach is different from <strong>compareTo(ChronoLocalDate).</strong> </p> <p> <strong>Syntax:</strong> </p> <pre> public boolean isEqual(ChronoLocalDate other) </pre> <p> <strong>CompareDatesExample4.java</strong> </p> <pre> import java.time.LocalDate; public class CompareDatesExample4 { public static void main(String[] args) { // Create LocalDate objects with dates LocalDate date1 = LocalDate.of(2020,9,29); LocalDate date2 = LocalDate.of(2020,12,07); // Print the Dates System.out.println(&apos;Date1: &apos; + date1); System.out.println(&apos;Date2: &apos; + date2); //comparing two dates if (date1.isAfter(date2)) { System.out.println(&apos;Date1 comes after Date2&apos;); } else if (date1.isBefore(date2)) { System.out.println(&apos;Date1 comes before Date2&apos;); } else if (date1.isEqual(date2)) { System.out.println(&apos;Both dates are equal&apos;); } } } </pre> <p> <strong>Output:</strong> </p> <pre> Date1: 2020-09-29 Date2: 2020-12-07 Date1 comes before Date2 </pre> <hr></date2>

Usando a classe LocalDate

Java fornece outro DataLocal classe para comparar dois LocalDate, LocalTime e LocalDateTime. É o membro dejava.timepacote. A classe fornece os métodos isBefore(), isAfter(), isEquals() e compareTo() para comparar datas. Esses métodos funcionam da mesma forma que os métodos before(), after() e equals() da classe Date e Calendar.

Vamos usar o Classe LocalDate em um exemplo para comparar duas datas.

No exemplo a seguir, usamos o método a seguir para comparar duas datas. Todos os métodos verificam as datas de acordo com a linha do horário local.

de(): É um método estático da classe LocalDate. Ele obtém uma instância de LocalDate no formato ano, mês e dia. Aceita três parâmetros ano, mês e data do tipo int. Ele retorna um LocalDate com a data especificada.

Sintaxe:

 public static LocalDate of(int year, int month, int dayOfMonth) 

onde:

ano: deve estar entre MIN_YEAR e MAX_YEAR.

casos de teste junit

mês: deve ser entre 1º (janeiro) a 12 (dezembro).

dataDoMês: deve estar entre 1 e 31.

Ele lança DateTimeException se o valor de qualquer parâmetro estiver fora do intervalo.

éAntes(): O método verifica se a data é anterior à data especificada. Ele analisa uma data (para comparar) como parâmetro. Retorna verdadeiro se e somente se a data for anterior à data especificada. Sua abordagem de comparação é diferente da compareTo(ChronoLocalDate).

Sintaxe:

 public boolean isBefore(ChronoLocalDate other) 

éDepois(): O método verifica se a data é anterior à data especificada. Ele analisa uma data (para comparar) como parâmetro. Retorna verdadeiro se e somente se a data for anterior à data especificada. Sua abordagem de comparação é diferente da compareTo(ChronoLocalDate) .

Sintaxe:

 public boolean isAfter(ChronoLocalDate other) 

é igual(): O método compara se as datas são iguais ou não. Se ambas as datas forem iguais, retorna verdadeiro, caso contrário, falso. Ele analisa uma data (para comparar) como parâmetro.

Retorna verdadeiro se e somente se a data for anterior à data especificada. Sua abordagem de comparação é diferente da compareTo(ChronoLocalDate).

Sintaxe:

 public boolean isEqual(ChronoLocalDate other) 

CompareDatesExample4.java

 import java.time.LocalDate; public class CompareDatesExample4 { public static void main(String[] args) { // Create LocalDate objects with dates LocalDate date1 = LocalDate.of(2020,9,29); LocalDate date2 = LocalDate.of(2020,12,07); // Print the Dates System.out.println(&apos;Date1: &apos; + date1); System.out.println(&apos;Date2: &apos; + date2); //comparing two dates if (date1.isAfter(date2)) { System.out.println(&apos;Date1 comes after Date2&apos;); } else if (date1.isBefore(date2)) { System.out.println(&apos;Date1 comes before Date2&apos;); } else if (date1.isEqual(date2)) { System.out.println(&apos;Both dates are equal&apos;); } } } 

Saída:

 Date1: 2020-09-29 Date2: 2020-12-07 Date1 comes before Date2