BAEL-3632 Using Instant to check if Two Java Dates are On Same Day
This commit is contained in:
parent
4d29d5ddcd
commit
babe8e87de
|
@ -1,8 +1,10 @@
|
|||
package com.baeldung.date.comparison;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
@ -23,6 +25,14 @@ public class DateComparisonUtils {
|
|||
return localDate1.isEqual(localDate2);
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingInstant(Date date1, Date date2) {
|
||||
Instant instant1 = date1.toInstant()
|
||||
.truncatedTo(ChronoUnit.DAYS);
|
||||
Instant instant2 = date2.toInstant()
|
||||
.truncatedTo(ChronoUnit.DAYS);
|
||||
return instant1.equals(instant2);
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingSimpleDateFormat(Date date1, Date date2) {
|
||||
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
|
||||
return fmt.format(date1)
|
||||
|
|
|
@ -1,13 +1,13 @@
|
|||
package com.baeldung.date.comparison;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Date;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DateComparisonUtilsUnitTest {
|
||||
|
||||
|
@ -23,6 +23,7 @@ public class DateComparisonUtilsUnitTest {
|
|||
@Test
|
||||
public void givenDatesWithDifferentTime_whenIsSameDay_thenReturnsTrue() {
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingLocalDate(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingInstant(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingCalendar(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingApacheCommons(day1Morning, day1Evening));
|
||||
|
@ -35,6 +36,9 @@ public class DateComparisonUtilsUnitTest {
|
|||
assertFalse(DateComparisonUtils.isSameDayUsingLocalDate(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingLocalDate(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingInstant(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingInstant(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Evening, day2Morning));
|
||||
|
||||
|
|
Loading…
Reference in New Issue