Skip to content

Commit

Permalink
Check for day range in script library
Browse files Browse the repository at this point in the history
  • Loading branch information
OreCruncher committed Feb 17, 2024
1 parent fee0e3b commit 8124b09
Showing 1 changed file with 31 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}
}

0 comments on commit 8124b09

Please sign in to comment.