logo

Come confrontare le date in Java

In Giava , mentre ci occupiamo di data E tempo , a volte ne abbiamo bisogno confrontare le date . IL confronto delle date in Java non è la stessa cosa del confronto tra due numeri. Quindi è un compito un po’ complicato confrontare due date in Java . Non è necessario implementare alcuna logica per farlo confrontare le date . Per rendere questo compito facile Giava fornisce confrontaCon(), prima(), dopo(), E equivale() metodo. In questa sezione impareremo come confrontare due date in Java .

Esistono quattro classi in Java che forniscono metodi per confrontare due date.

  • Utilizzando Paragonare a() Metodo
  • Utilizzando Data Classe
  • Utilizzando Calendario Classe
  • Utilizzando LocalDate Classe

Utilizzando il metodo Date.compareTo()

Classe Data Java fornisce diversi metodi relativi all'ora e alle date. È una classe dijava.utilpacchetto. La classe implementa le interfacce Serializable, Cloneable e Comparable.

pitone o

Per il confronto di due date, la classe fornisce Paragonare a() metodo . Confronta le date per l'ordinazione. Analizza una data (da confrontare) come parametro. Lancia NullPointerException se la data dell'argomento è nulla.

Sintassi:

 public int compareTo(Date anotherDate) 

Restituisce valori interi:

    0:se entrambe le date sono uguali.Un valore inferiore a 0:se la data è precedente alla data dell'argomento.Un valore maggiore di 0:se la data è successiva alla data dell'argomento.

Ricordare: Se hai a che fare con la data in Java, non dimenticare di importare java.text.SimpleDateFormat, java.text.ParseException,java.util.Date.

Implementiamo il metodo compareTo() e confrontiamo due date.

Nell'esempio seguente, abbiamo creato un'istanza di SimpleDateFormat classe che ci permette di prendere diversi formati di data. Successivamente, abbiamo preso due variabili data1 E data2 di tipo Data. Utilizzando il analizzare() metodo della classe SimpleDateFormat, abbiamo analizzato le date da confrontare. Il metodo restituisce a data analizzato dalla stringa. Abbiamo passato le variabili date1 e date2 di tipo Date nel file formato() metodo. Il metodo fornisce la stringa data/ora formattata.

Per confrontare le due date, abbiamo utilizzato il Paragonare a() metodo. Se entrambe le date sono uguali, viene stampato Entrambe le date sono uguali. Se data1 è maggiore di data2 , viene stampato La data 1 viene dopo la data 2 . Se data1 è inferiore a data2 , viene stampato La data 1 viene dopo la data 2 .

ConfrontaDateEsempio1.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)>

Utilizzo della classe data

La classe di date Java fornisce il metodo before() , after() e equals() per confrontare due date.

Prima(): Il metodo verifica che la data sia precedente o meno alla data specificata. Analizza un parametro di tipo Date. Ritorna VERO se e solo se l'istante di tempo rappresentato da questo oggetto Date è strettamente precedente all'istante rappresentato da quando, falso Altrimenti.

Sintassi:

10 milioni
 public boolean before(Date when) 

Lancia NullPointerException se quando è nullo.

Dopo(): Il metodo verifica che la data sia successiva o meno alla data specificata. Analizza un parametro di tipo Date. Ritorna VERO se e solo se l'istante di tempo rappresentato da questo oggetto Date è strettamente successivo all'istante rappresentato da quando, falso Altrimenti.

Sintassi:

 public boolean after(Date when) 

Lancia NullPointerException se quando è nullo.

equivale(): Il metodo verifica (confronta) l'uguaglianza di due date. Sostituisce il metodo equals() della classe Object. Restituisce vero se gli oggetti sono uguali, altrimenti restituisce falso. Pertanto, gli oggetti Date saranno uguali se e solo se il metodo getTime() restituisce lo stesso valore long per entrambe le date.

Sintassi:

 public boolean equals (Object obj) 

Usiamo il metodo sopra spiegato in un esempio e confrontiamo due date con l'aiuto di questi metodi.

carattere in int in Java

ConfrontaDatesExample2.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,>

Utilizzo della classe Calendario

Come la classe Java Date, il file Calendario classe fornisce anche i metodi before() , after() e equals() . Tutti e tre i metodi hanno la stessa firma, come abbiamo spiegato sopra.

Usiamo la classe Calendar e confrontiamo due date con l'aiuto dei metodi after(), before() ed equals().

Nell'esempio seguente, abbiamo utilizzato lo stesso metodo utilizzato nell'esempio precedente, ad eccezione di getIstanza() E setTime() metodi.

getIstanza(): È un metodo statico del Calendario. Restituisce un calendario utilizzando il fuso orario e le impostazioni internazionali predefiniti.

Sintassi:

 public static Calendar getInstance() 

setTime(): Il metodo imposta l'ora del calendario in base alla data specificata. Analizza un parametro di tipo Date.

Sintassi:

hiba bukhari
 public final void setTime(Date date) 

ConfrontaDatesExample3.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>

Utilizzo della classe LocalDate

Java ne fornisce un altro LocalDate classe per confrontare due LocalDate, LocalTime e LocalDateTime. È il membro dijava.timepacchetto. La classe fornisce il metodo isBefore(), isAfter(), isEquals() e compareTo() per confrontare le date. Questi metodi funzionano allo stesso modo del metodo before(), after() ed equals() delle classi Date e Calendar.

Usiamo il Classe LocalDate in un esempio per confrontare due date.

Nell'esempio seguente, abbiamo utilizzato il seguente metodo per confrontare due date. Tutti i metodi controllano le date in base alla linea dell'ora locale.

Di(): È un metodo statico della classe LocalDate. Ottiene un'istanza del formato LocalDate anno, mese e giorno. Accetta tre parametri anno, mese e data di tipo int. Restituisce un LocalDate con la data specificata.

Sintassi:

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

Dove:

anno: deve essere compreso tra MIN_YEAR e MAX_YEAR.

mese: deve essere compreso tra il 1 (gennaio) e il 12 (dicembre).

datdel mese: deve essere compreso tra 1 e 31.

svuotare la cache npm

Genera DateTimeException se il valore di qualsiasi parametro non è compreso nell'intervallo.

èPrima(): Il metodo verifica che la data sia precedente alla data specificata. Analizza una data (da confrontare) come parametro. Restituisce vero se e solo se la data è precedente alla data specificata. Il suo approccio comparativo è diverso da confrontaCon(ChronoLocalDate).

Sintassi:

 public boolean isBefore(ChronoLocalDate other) 

èDopo(): Il metodo verifica che la data sia precedente alla data specificata. Analizza una data (da confrontare) come parametro. Restituisce vero se e solo se la data è precedente alla data specificata. Il suo approccio comparativo è diverso da confrontaCon(ChronoLocalDate) .

Sintassi:

 public boolean isAfter(ChronoLocalDate other) 

è uguale(): Il metodo confronta le date se sono uguali o meno. Se entrambe le date sono uguali restituisce vero, altrimenti falso. Analizza una data (da confrontare) come parametro.

Restituisce vero se e solo se la data è precedente alla data specificata. Il suo approccio comparativo è diverso da confrontaCon(ChronoLocalDate).

Sintassi:

 public boolean isEqual(ChronoLocalDate other) 

ConfrontaDatesExample4.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;); } } } 

Produzione:

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