logo

Sådan sammenlignes datoer i Java

I Java , mens vi beskæftiger os med dato og tid , nogle gange har vi brug for det sammenligne datoer . Det sammenligning af datoer i Java er ikke det samme som sammenligning af to tal. Så det er en lidt vanskelig opgave sammenligne to datoer i Java . Vi behøver ikke at implementere nogen logik til sammenligne datoer . For at gøre denne opgave let Java giver sammenligneTil(), før(), efter(), og lige med() metode. I dette afsnit skal vi lære hvordan man sammenligner to datoer i Java .

Der er fire klasser i Java, der giver metoder til at sammenligne to datoer.

  • Ved brug af sammenligne med() Metode
  • Ved brug af Dato Klasse
  • Ved brug af Kalender Klasse
  • Ved brug af LocalDate Klasse

Brug af Date.compareTo()-metoden

Java Dato klasse giver forskellige metoder relateret til tidspunkt og datoer. Det er en klasse afjava.utilpakke. Klassen implementerer grænseflader, der kan serialiseres, klones og sammenlignes.

Til sammenligning af to datoer giver klassen sammenligne med() metode. Den sammenligner datoer for bestilling. Den analyserer en dato (der skal sammenlignes) som en parameter. Det kaster NullPointerException hvis argumentdatoen er nul.

Syntaks:

 public int compareTo(Date anotherDate) 

Det returnerer heltalsværdier:

    0:hvis begge datoer er ens.En værdi mindre end 0:hvis datoen er før argumentdatoen.En værdi større end 0:hvis datoen er efter argumentdatoen.

Husk: Hvis du har med dato at gøre i Java, så glem ikke at importere java.text.SimpleDateFormat, java.text.ParseException,java.util.Dato.

checkout med git

Lad os implementere compareTo()-metoden og sammenligne to datoer.

I det følgende eksempel har vi oprettet en forekomst af SimpleDateFormat klasse, der giver os mulighed for at tage forskellige datoformater. Derefter har vi taget to variable dato 1 og dato 2 af typen Dato. Ved at bruge parse() metoden i SimpleDateFormat-klassen, har vi analyseret datoerne for at sammenligne. Metoden returnerer en dato parset fra strengen. Vi har passeret variablerne date1 og date2 af typen Date i format() metode. Metoden giver den formaterede dato/tidsstreng.

Til at sammenligne de to datoer har vi brugt sammenligne med() metode. Hvis begge datoer er ens, udskrives den Begge datoer er lige store. Hvis dato1 er større end dato2 , det udskriver Dato 1 kommer efter dato 2 . Hvis dato1 er mindre end dato2 , det udskriver Dato 1 kommer efter dato 2 .

Sammenlign DatoerEksempel1.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)>

Brug af datoklasse

Java-datoklassen giver metoden before(), after() og equals() til at sammenligne to datoer.

Før(): Metoden kontrollerer, at datoen kommer før den angivne dato eller ej. Den analyserer en parameter af typen Dato. Det vender tilbage rigtigt hvis og kun hvis det tidspunkt, der repræsenteres af dette Dato-objekt, er strengt tidligere end det øjeblik, der repræsenteres af hvornår, falsk Ellers.

Syntaks:

 public boolean before(Date when) 

Det kaster NullPointerException hvis hvornår er nul.

efter(): Metoden kontrollerer, at datoen kommer efter den angivne dato eller ej. Den analyserer en parameter af typen Dato. Det vender tilbage rigtigt hvis og kun hvis det tidspunkt, der repræsenteres af dette Dato-objekt, er strengt senere end det øjeblik, der repræsenteres af hvornår, falsk Ellers.

Syntaks:

fjern første tegn excel
 public boolean after(Date when) 

Det kaster NullPointerException hvis hvornår er nul.

lige med(): Metoden kontrollerer (sammenlign) ligheden mellem to datoer. Det tilsidesætter equals()-metoden i Object-klassen. Det returnerer sandt, hvis objekterne er ens, ellers returnerer falsk. Derfor vil Dato-objekterne være ens, hvis og kun hvis metoden getTime() returnerer den samme lange værdi for begge datoer.

Syntaks:

 public boolean equals (Object obj) 

Lad os bruge den ovenfor forklarede metode i et eksempel og sammenligne to datoer ved hjælp af disse metoder.

lineær søgning i 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,>

Brug af kalenderklasse

Ligesom Java Date-klassen Kalender klasse giver også metoderne before(), after() og equals() . Alle tre metoder har samme signatur, som vi har forklaret ovenfor.

Lad os bruge klassen Kalender og sammenligne to datoer ved hjælp af metoden after(), before() og equals().

I det følgende eksempel har vi brugt den samme metode, som blev brugt i det foregående eksempel, undtagen getInstance() og fastsat tidspunkt() metoder.

getInstance(): Det er en statisk metode i kalenderen. Det returnerer en kalender ved hjælp af standardtidszonen og lokaliteten.

Syntaks:

 public static Calendar getInstance() 

fastsat tidspunkt(): Metoden indstiller kalendertiden i henhold til den angivne dato. Den analyserer en parameter af typen Dato.

Syntaks:

simpel datoformater i java
 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>

Brug af LocalDate Class

Java giver en anden LocalDate klasse for at sammenligne to LocalDate, LocalTime og LocalDateTime. Det er medlem afjava.tidpakke. Klassen giver metoden isBefore(), isAfter(), isEquals() og compareTo()-metoden til at sammenligne datoer. Disse metoder fungerer på samme måde som metoden before(), after() og equals() i klassen Dato og Kalender.

Lad os bruge LocalDate klasse i et eksempel for at sammenligne to datoer.

I det følgende eksempel har vi brugt følgende metode til at sammenligne to datoer. Alle metoderne kontrollerer datoerne i henhold til lokaltidslinjen.

af(): Det er en statisk metode af LocalDate-klassen. Den henter en forekomst af LocalDate fra år, måned og dag. Den accepterer tre parametre år, måned og dato for type int. Det returnerer en LocalDate med den angivne dato.

Syntaks:

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

hvor:

år: skal være mellem MIN_YEAR og MAX_YEAR.

måned: skal være mellem 1 (januar) til 12 (december).

datOfMonth: skal være mellem 1 og 31.

Det kaster DateTimeException, hvis værdien af ​​en parameter er uden for rækkevidde.

erFør(): Metoden kontrollerer, at datoen er før den angivne dato. Den analyserer en dato (for at sammenligne) som en parameter. Det returnerer sandt, hvis og kun hvis datoen er før den angivne dato. Dens sammenligningstilgang er forskellig fra compareTo(ChronoLocalDate).

Syntaks:

 public boolean isBefore(ChronoLocalDate other) 

erEfter(): Metoden kontrollerer, at datoen er før den angivne dato. Den analyserer en dato (for at sammenligne) som en parameter. Det returnerer sandt, hvis og kun hvis datoen er før den angivne dato. Dens sammenligningstilgang er forskellig fra sammenligneTil(ChronoLocalDate) .

streng til int

Syntaks:

 public boolean isAfter(ChronoLocalDate other) 

er Lige(): Metoden sammenligner datoerne er ens eller ej. Hvis begge datoer er ens, returnerer det sandt, ellers falsk. Den analyserer en dato (for at sammenligne) som en parameter.

Det returnerer sandt, hvis og kun hvis datoen er før den angivne dato. Dens sammenligningstilgang er forskellig fra compareTo(ChronoLocalDate).

Syntaks:

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

Produktion:

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