logo

Як порівняти дати в Java

в Java , поки ми займаємося дата і час , іноді нам потрібно порівняти дати . The порівняння дат на Java не те саме, що порівняння двох чисел. Отже, це трохи складне завдання порівняти дві дати в Java . Нам не потрібно застосовувати жодної логіки порівняти дати . Щоб полегшити це завдання Java забезпечує compareTo(), before(), after(), і дорівнює() метод. У цьому розділі ми будемо вчитися як порівняти дві дати в Java .

У Java є чотири класи, які надають методи для порівняння двох дат.

  • Використання порівняти() метод
  • Використання Дата Клас
  • Використання Календар Клас
  • Використання Місцева дата Клас

Використання методу Date.compareTo().

Клас Java Date надає різні методи, пов’язані з часом і датами. Це класjava.utilпакет. Клас реалізує інтерфейси Serializable, Cloneable і Comparable.

Для порівняння двох дат клас надає порівняти() метод . Він порівнює дати для замовлення. Він аналізує дату (для порівняння) як параметр. Це кидає NullPointerException якщо дата аргументу нульова.

Синтаксис:

 public int compareTo(Date anotherDate) 

Він повертає цілі значення:

    0:якщо обидві дати рівні.Значення менше 0:якщо дата передує даті аргументу.Значення більше 0:якщо дата стоїть після дати аргументу.

Пам'ятайте: Якщо ви маєте справу з датою в Java, не забудьте імпортувати java.text.SimpleDateFormat, java.text.ParseException,java.util.Date.

Давайте реалізуємо метод compareTo() і порівняємо дві дати.

У наступному прикладі ми створили екземпляр SimpleDateFormat клас, який дозволяє нам приймати різні формати дати. Після цього ми взяли дві змінні дата1 і дата2 типу Дата. За допомогою розібрати() метод класу SimpleDateFormat, ми розібрали дати для порівняння. Метод повертає a дата розібрати з рядка. Ми передали змінні date1 і date2 типу Date у формат() метод. Метод дає відформатований рядок дати/часу.

java ядро ​​java

Для порівняння двох дат ми використали порівняти() метод. Якщо обидві дати рівні, друкується Обидві дати рівні. Якщо дата1 більша за дату2 , він друкує Дата 1 йде після дати 2 . Якщо дата1 менша за дату2 , він друкує Дата 1 йде після дати 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)>

Використання класу дати

Клас дати Java надає метод before(), after() і equals() для порівняння двох дат.

перед(): Метод перевіряє, чи передує дата вказаній даті чи ні. Він аналізує параметр типу Date. Воно повертається правда якщо і тільки якщо момент часу, представлений цим об’єктом Date, строго раніше, ніж момент, представлений when, помилковий інакше.

Синтаксис:

зразок коду c#
 public boolean before(Date when) 

Це кидає NullPointerException якщо коли дорівнює нулю.

після (): Метод перевіряє, чи настає дата після зазначеної дати чи ні. Він аналізує параметр типу Date. Воно повертається правда тоді і тільки якщо момент часу, представлений цим об’єктом Date, строго пізніший за момент, представлений when, помилковий інакше.

Синтаксис:

 public boolean after(Date when) 

Це кидає NullPointerException якщо коли дорівнює нулю.

дорівнює(): Метод перевіряє (порівнює) рівність двох дат. Він замінює метод equals() класу Object. Він повертає true, якщо об’єкти однакові, інакше повертає false. Таким чином, об’єкти Date будуть рівними тоді і тільки тоді, коли метод getTime() повертає однакове довге значення для обох дат.

Синтаксис:

 public boolean equals (Object obj) 

Скористаємося вищеописаним методом у прикладі та порівняємо дві дати за допомогою цих методів.

перефразуйте Редьярда Кіплінга

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

Використання Календарного класу

Як і клас Java Date, Календар клас також надає методи before(), after() і equals(). Усі три методи мають однаковий підпис, як ми пояснювали вище.

Давайте скористаємося класом Calendar і порівняємо дві дати за допомогою методів after(), before() і equals().

У наступному прикладі ми використали той самий метод, що й у попередньому прикладі, за винятком getInstance() і setTime() методи.

getInstance(): Це статичний метод календаря. Він повертає календар із використанням часового поясу та мови за умовчанням.

Синтаксис:

 public static Calendar getInstance() 

setTime(): Метод встановлює календарний час відповідно до вказаної дати. Він аналізує параметр типу Date.

Синтаксис:

висота kat timpf
 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>

Використання класу LocalDate

Java пропонує інше Місцева дата клас для порівняння двох LocalDate, LocalTime і LocalDateTime. Це членjava.timeпакет. Клас надає метод isBefore(), isAfter(), isEquals() і compareTo() для порівняння дат. Ці методи працюють так само, як і методи before(), after() і equals() класу Date і Calendar.

Давайте використовувати Клас LocalDate у прикладі для порівняння двох дат.

У наступному прикладі ми використали такий метод для порівняння двох дат. Усі методи перевіряють дати відповідно до місцевого часу.

з(): Це статичний метод класу LocalDate. Він отримує екземпляр LocalDate у формі року, місяця та дня. Він приймає три параметри рік, місяць і дата типу int. Він повертає LocalDate із зазначеною датою.

Синтаксис:

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

де:

рік: має бути від MIN_YEAR до MAX_YEAR.

місяць: має бути між 1 (січень) і 12 (грудень).

datOfMonth: має бути від 1 до 31.

Він викидає DateTimeException, якщо значення будь-якого параметра виходить за межі діапазону.

isBefore(): Метод перевіряє, чи дата передує вказаній даті. Він аналізує дату (для порівняння) як параметр. Він повертає true тоді і тільки тоді, коли дата передує вказаній даті. Його підхід до порівняння відрізняється від compareTo(ChronoLocalDate).

Синтаксис:

 public boolean isBefore(ChronoLocalDate other) 

isAfter(): Метод перевіряє, чи дата передує вказаній даті. Він аналізує дату (для порівняння) як параметр. Він повертає true тоді і тільки тоді, коли дата передує вказаній даті. Його підхід до порівняння відрізняється від compareTo(ChronoLocalDate) .

Синтаксис:

 public boolean isAfter(ChronoLocalDate other) 

isEqual(): Метод порівнює дати, рівні чи ні. Якщо обидві дати рівні, повертається true, інакше – false. Він аналізує дату (для порівняння) як параметр.

java хвіст

Він повертає true тоді і тільки тоді, коли дата передує вказаній даті. Його підхід до порівняння відрізняється від compareTo(ChronoLocalDate).

Синтаксис:

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

Вихід:

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