Skip to content

Commit

Permalink
Added some convenient methods for DateTimeType
Browse files Browse the repository at this point in the history
Signed-off-by: Gaël L'hopital <gael@lhopital.org>
  • Loading branch information
clinique committed Jun 18, 2024
1 parent 2aacdcd commit cdfceb1
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.time.zone.ZoneRulesException;
import java.util.Locale;

Expand All @@ -37,6 +38,7 @@
* @author Wouter Born - increase parsing and formatting precision
* @author Laurent Garnier - added methods toLocaleZone and toZone
* @author Gaël L'hopital - added ability to use second and milliseconds unix time
* @author Gaël L'hopital - added isToday, isTomorrow, isYesterday, sameDay
*/
@NonNullByDefault
public class DateTimeType implements PrimitiveType, State, Command {
Expand Down Expand Up @@ -248,4 +250,25 @@ private ZonedDateTime parse(String value) throws DateTimeParseException {

return date;
}

public boolean isToday() {
return sameDay(ZonedDateTime.now());
}

public boolean isTomorrow() {
return sameDay(ZonedDateTime.now().plusDays(1));
}

public boolean isYesterday() {
return sameDay(ZonedDateTime.now().minusDays(1));
}

public boolean sameDay(DateTimeType other) {
return sameDay(other.zonedDateTime);
}

public boolean sameDay(ZonedDateTime other) {
return zonedDateTime.truncatedTo(ChronoUnit.DAYS)
.isEqual(other.withZoneSameLocal(zonedDateTime.getZone()).truncatedTo(ChronoUnit.DAYS));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
* @author Erdoan Hadzhiyusein - Added ZonedDateTime tests
* @author Laurent Garnier - Enhanced tests
* @author Gaël L'hopital - added ability to use second and milliseconds unix time
* @author Gaël L'hopital - added isToday, isTomorrow, isYesterday tests
*/
@NonNullByDefault
public class DateTimeTypeTest {
Expand Down Expand Up @@ -290,6 +291,21 @@ public void epochTest() {
assertThat(epochStandard, is(zdtStandard));
}

@Test
public void relativeTest() {
DateTimeType dt1 = new DateTimeType("2019-06-12T17:30:00Z");
DateTimeType dt2 = new DateTimeType("2019-06-12T00:00:00+0000");

assertTrue(dt1.sameDay(dt2));
assertTrue(new DateTimeType().isToday());

DateTimeType now = new DateTimeType();
DateTimeType tomorrow = new DateTimeType(now.getZonedDateTime().plusHours(24));
DateTimeType yesterday = new DateTimeType(now.getZonedDateTime().minusHours(24));
assertTrue(tomorrow.isTomorrow());
assertTrue(yesterday.isYesterday());
}

@ParameterizedTest
@MethodSource("parameters")
public void createDate(ParameterSet parameterSet) {
Expand Down

0 comments on commit cdfceb1

Please sign in to comment.