diff --git a/src/main/java/org/orecruncher/dsurround/lib/scripting/LibraryFunctions.java b/src/main/java/org/orecruncher/dsurround/lib/scripting/LibraryFunctions.java index e1b5ff7b..ef8e4d4c 100644 --- a/src/main/java/org/orecruncher/dsurround/lib/scripting/LibraryFunctions.java +++ b/src/main/java/org/orecruncher/dsurround/lib/scripting/LibraryFunctions.java @@ -2,17 +2,22 @@ import org.jetbrains.annotations.Nullable; import org.orecruncher.dsurround.lib.Library; +import org.orecruncher.dsurround.lib.di.ContainerManager; import org.orecruncher.dsurround.lib.platform.IPlatform; +import org.orecruncher.dsurround.lib.system.ISystemClock; +import java.time.*; import java.util.Objects; import java.util.regex.Pattern; /** * Library functions exposed via the JavaScript engine. They are not directly used by code. */ +@SuppressWarnings("unused") public final class LibraryFunctions { private static final IPlatform PLATFORM = Library.PLATFORM; + private static final ISystemClock SYSTEM_CLOCK = ContainerManager.resolve(ISystemClock.class); public Object iif(final boolean flag, @Nullable final Object trueResult, @Nullable final Object falseResult) { return flag ? trueResult : falseResult; @@ -40,4 +45,30 @@ public boolean isBetween(final double value, final double min, final double max) public boolean isModLoaded(final String mod) { return PLATFORM.isModLoaded(mod); } + + public boolean isCurrentDateInRangeOf(int month, int day, int dayRange) { + try { + // Get the current Utc time. Assume the test date is the same year. + var theNow = LocalDate.ofInstant(SYSTEM_CLOCK.getUtcNow(), ZoneOffset.UTC); + var testDate = LocalDate.of(theNow.getYear(), month, day); + + // If the test date is before the time window, it means the range is in the future + var begin = theNow.minusDays(dayRange); + if (begin.isAfter(testDate)) + return false; + + // So the test date is after the beginning of the window. See if it is before + // the end of the window. If so, it's in range. + var end = theNow.plusDays(dayRange); + if (!end.isBefore(testDate)) + return true; + + // So the range looks like it is in the past. It's possible that we are dealing with an end of year thing + // like new years. Handle that by adding one year to the test date and re-evaluate. + testDate = testDate.plusYears(1); + return !(begin.isAfter(testDate) || end.isBefore(testDate)); + } catch (Throwable ignore) { + } + return false; + } } \ No newline at end of file