0% found this document useful (0 votes)
24 views7 pages

Z 17

java
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
24 views7 pages

Z 17

java
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 7
oart2023 20:17 Comparing Dates in Java | Baoldung “ Comparing Dates in Java Secure a Simple Spring MVC Apy {Simple Remember-Me Flow Y thitos//adsfreestarcom/? Last updated Apel :9, 2020 &. | wiitten by Drazon Nikolic hitps//wwwbaeldungcom/author/ CHECK OUT THE COURSE (/\s-course-start) Read the blog to learn about your next steps WV wos (hllps//ads freestarcom/? m_campaign-branding&utm_medium-banner&utm_source-baeldung.com&utm_content-baeldung_incontent 2 1, Introduction In this tutorial, well focus on how to compare dates using the Java 8 Date/Time API (/java-8-date-time- Intro}, Well dive into different methods to check whether two dates are equal and how to compr~>) dates. v nitpsdlwww.baeldung.comjava-comparing-dates we oars12029 20:17 Comparing Dates in Java | Bacldung 2. Comnaring Dates, The basic way to express a date in Java is LocalDate. Let's consider two LocalDate object instances, representing the 10th of August 2019 and the 1st of July 2019. ocalDate,of (2019, 8) 18); Locatoate.of(2029, 7, 2); Localoate firstoate Localdate secondvate We're going to compare two LocalDate objects by utilizing the isAfter(), isBefore( and isEquald ‘methods, as well as equals()and compareTod. ‘We use the isAfterd method to check ifthe date instance is after the other specified date, Therefore. the next JUnit assertion will pass: | ssesoeceratnce street, Seen Analogously, the method isBefored checks if the date instance is before the other specified date: ihttps//ads freestarcom/? ‘The method isEquall) checks if date represents the same point on the local timeline as the other specified date assertThat(Firstoate.istqual(Firstoate), is(true)); assertThat (FirstDate, isEqual(seconddate), is(false)); 2.1, Comparing Dates Using the Comparable Interface ‘The equals) method will give the same result as ‘sEqual0, but only if the argument passed is of the same type (in this case, LocalDate’ | sserstancriatntesnsttesontoty, see ‘The isEqual0 method can be used instead to compare with objects ofa different type, such as JapaneseDate, ThaiBuddhistDate, etc. We can compare two date instances by using the compare7ov/ method. as defined by the Comparable interface: assertThat(Firstate.conpareto(seconddate), 45(1))5 assertThat (secondDate.compareTo(firstDate), 18(-1))5 itpsmewbaeldung.comljava-comparing-dates oars12029 20:17 Comparing Dates in Java | Bacldung 3. Com”aring Date |pstances Containing the Time Component This section will explain how to compare two LocalDateTime ins the date as wellas the time component, 1ces. LocalDateTime instances contain Similarly to LocalDate, we're comparing two LocalDateTime instances with the methods isAfter0, isBefore() and isEqual0. Addilionally, equals and compareTod can be used in a similar fashion as, described for LocalDate. Likewise, we can use the same methods for comparing two ZonedDatetime instances. Let's compare 8:00 capers cnt = ZonedDateTime.of (2819, 8, 18, 8, 8, 8, 8, ZoneTd.of("America/New York")); 0 ZonecoateTine tineTnBerLin = Zoneddaterine.of (2819, 8, 10, 14, 8, 8, 8, ZoneIé.of("Europe/BerLin")) ; assert That (timeToNewvork.isAfter(timeznBerlin), 1s(False)) assertthat timeZnNework.1sBefore(timernBertin}, is(fatse)); assertThat (timeznNewYork, isEqual(timeZnBer tin), is(true)); ‘Although both ZonedDateTimeinstances represent the same moment in time, they do not represent equal. Java objects. They have diferent LocalDatelime and Zoneld fields internally 4. Additional Comparisons Let's create a simple utility class for slightly more complex comparisons. Firstly, well check if instances of Local(DateTime and LocalDate are on the same day: nitpsdlwww.baeldung.comjava-comparing-dates an oart2023 20.17 Comparing Dates in Java | Baoldung weblic st.ric sc.8" “ins meDbflLocatvaterine tinestamp, oO Locatbate local0ateToConpare) { return timestamp. toLocalDate().istqual (IocatbateTecompare) 5 ‘Secondly, well check if two instances of LocalDateTime are on the same day: public static boolean ‘sSaneday(LocalvateTine tinestamp, oO LocalDateTine timestaspTaconpare) { return timestanp.truncatedTo(DAYS) {sCqual (timestanpToConpare.truncatedTo(OAYS)) ‘The truncatedTo(TemporalUnit) method truncates a date on the given level, which in our example is a day, Thirdly, we can implement a comparison at the level of an hour: public static boclean ‘sSaneHour(Local0aterize timestamp, LocatoateTine timestaspToconpare) { return timestanp.truncatedTo(HOURS) ‘sEqual (timestanpToConpare.truncatedTo (HOURS)) : Finally, in a similar way, we can check iftwo ZonedDateTime instances happen within the same hour. public static boclean “sSancHour(ZoneddateTise zonedTinestanp, ZoneddateTine zonedTinestampToConpare) { — return zonedTinestaep. truncatedTo (HOURS) '{sEqual (zonedTimestampToconpare.truncatedTo(HOURS)) ; \We can see that two ZonedDateTime objects are actually happening within the same hour, even if their local times are different (8:30 and 14:00, respectively ZonecoateTine zonedTinestanp = ZoneddateTine.of (2019, 8, 10, 8, 30, 0, 0, ZoneIé.of ("Anerica/New York"); ZonecoateTine zonedTimestanpToCompare ZonedoateTine.of (2813, 8, 18, 14, 8, 8, 8, ZoneTé.of ("Eurape/BerLin")); assert That (DateTineConparisonUtsts- “isSanetiour(zonedTimestanp, 2onedTimestanpTaconpare), 1s(true)); 5. Comparison in the Old Java Date API Bofore Java 8, we had to use java util Date and java.util Calendar classes for manipulating date/time information, The design of the old Java Date API has many flaws, such as being complex and not thread- safe. The java.util Date instance represents an ‘instant in time" and not a real date ‘One of the solutions was to use the Joda Time (/joda-time) library. Since the release of Java 8, itis recommended to migrate to the Java 8 Date/Time API (/migrating-to-java-8-date-time-ap. Similarly to LocalDate and LocalDateTime, both java.util.Date and java.util.calendar objects have after0, before(, compareTol) and equals() methods for comparing two date instances. The dates are compared as the instants in time, on the level of a millisecon: itpsmewbaeldung.comljava-comparing-dates an oart2023 20:17 Comparing Dates in Java | Baoldung “ (https //ads freestarcom/? Date firstoate Date secondbate toate(LocalDateTime.of(2018, 8, 18, 8, 68, 89))5 topate(Locatvaterine.of (2819, 8, 15, 8, 69, 08)); assertThat (FirstDate.ofter (secondDate), is(false)); assertThat(Firstoate.before(secondoate) , is(true)); assertThat (Firstvate,conpareTo(secondDate), 15(-1))5 assertThat FirstDate.equals(seconddate), 15(False)); For more complex comparisons, we can use DateUtils from the Apache Commons Lang {https//mvnrepository.com/artifact/org.apache.commons/commons-lang3) library. This class contains many handy methods for dealing with Date and Calendar objects: public static bocteen ‘ssaneney(0ate date, Date dateTeCompere) o return DateUtte SeSaneay Gate, dateTocompare)s > public static boolean ‘sSaneHour(Date date, Date dateTacompare) { return DateUtils.truncatedEquals(date, dateToConpare, Calendar HOUR); y ‘To compare date objects originating from the different APIs, we should! first do a proper conversion and. ‘only then apply the comparison. We can find more detalls in our Convert Date to LocalDate or LocalDateTime and Back (/java-date-to-localdate-and-localdatetime) tutorial, 6. Conclusion In this article, weve explored different ways of comparing date instances in Java, ‘The Java 8 Date/Time classes have rich APIs for comparing dates, with or without time and time zones. Weve also seen how to compare dates on the granularity of a day, hour, minute, etc. ‘AlLof the code snippets mentioned in the article, including additional examples, are available over on GitHub thttps//github.com/eugenp/tutorials/tree/master/core-java-modules/core-java-8-datetimel, Get started with Spring 5 and Spring Boot 2, through the Learn Spring course: >> CHECK OUT THE COURSE (/1s-course-end) itpsmewbaeldung.comljava-comparing-dates sr oart2023 20:17 ‘Comparing Dates in Java | Baeldung Learning to build your API with Spring? Downtoad the E-book (/rest-api-spring-guide) ‘Comments are closed on this article! ‘COURSES, [ALL COURSES (/ALL-COURSES) [ALL BULK COURSES VALL-SULK-COURSES) THE COURSES PLATFORM (HTTPS:/COURSES BAELDUNG.COM: SERIES JAVA BACK TO ASICS! TUTORIAL VJAVACTUTORIAL) AOACHE HITPCLIENT TUTORIAL (/HTTECLIENT-GUIDEI REST WITH SPRING TUTORIAL (/REST-WITHASPRING-SFRIES! SECURITY WHT SPRING /SECURITY-SPRING! SPRING RACTIVE TUTORIALS V/SPRING.REACTIVE-CUIDE! ¥ htipsifwnww.bacldung,comava-comparing-dates oart2023 20:17 “ ABOUT THE FULLARCHIVE FULL ARCHIVE ‘OUR PARTNERS {/PARTNERS) PRIVACY POLICY V/PRIVACY-POLICY! itpsmewbaeldung.comljava-comparing-dates Comparing Dates in Java | Baoldung W

You might also like