Skip to content

Timezone Support #7887

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 25 commits into
base: dev/feature
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package ch.njol.skript.conditions;

import ch.njol.skript.Skript;
import ch.njol.skript.doc.*;
import ch.njol.skript.lang.Condition;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.util.Kleenean;
import org.bukkit.event.Event;
import org.jetbrains.annotations.Nullable;

import java.time.DateTimeException;
import java.time.ZoneId;

@Name("Is Timezone Valid")
@Description("Checks if a timezone is valid.")
@Example("""
set {_timezone} to "America/New_York"
if timezone {_timezone} is valid:
set {_date} to now in timezone {_timezone}
""")
@Since("INSERT VERSION")
public class CondIsTimezoneValid extends Condition {

static {
Skript.registerCondition(CondIsTimezoneValid.class, "time[ ]zone[s] %strings% (is|are) [negate:in]valid");
}

private Expression<String> timezones;
private boolean isNegated;

@Override
public boolean init(Expression<?>[] expressions, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) {
timezones = (Expression<String>) expressions[0];
isNegated = parseResult.hasTag("negate");
return true;
}

@Override
public boolean check(Event event) {
for (String timezone : timezones.getAll(event)) {
if (timezone == null) {
return isNegated;
}

try {
ZoneId.of(timezone);
} catch (DateTimeException e) {
return isNegated;
}
}

return !isNegated;
}

@Override
public String toString(@Nullable Event event, boolean debug) {
return "timezone " + timezones.toString(event, debug) + " is " + (isNegated ? "in" : "") + "valid";
}

}
22 changes: 16 additions & 6 deletions src/main/java/ch/njol/skript/expressions/ExprAllTimezones.java
Original file line number Diff line number Diff line change
@@ -1,37 +1,47 @@
package ch.njol.skript.expressions;

import ch.njol.skript.Skript;
import ch.njol.skript.doc.Description;
import ch.njol.skript.doc.Example;
import ch.njol.skript.doc.Name;
import ch.njol.skript.doc.Since;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.ExpressionType;
import ch.njol.skript.lang.SkriptParser;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.skript.lang.util.SimpleExpression;
import ch.njol.util.Kleenean;
import org.bukkit.event.Event;
import org.jetbrains.annotations.Nullable;

import java.time.ZoneId;

@Name("All Timezones")
@Description("Returns a list of all timezones that can be used in the <a href='#ExprNow'>now</a> expression.")
@Example("set {_timezones::*} to all timezones")
@Since("INSERT VERSION")
public class ExprAllTimezones extends SimpleExpression<String> {

static {
Skript.registerExpression(ExprAllTimezones.class, String.class, ExpressionType.SIMPLE, "all time[ ]zones");
Skript.registerExpression(ExprAllTimezones.class, String.class, ExpressionType.SIMPLE, "all [of [the]] time[ ]zones");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Skript.registerExpression(ExprAllTimezones.class, String.class, ExpressionType.SIMPLE, "all [of [the]] time[ ]zones");
Skript.registerExpression(ExprAllTimezones.class, String.class, ExpressionType.SIMPLE, "[the|all [[of] the]] time[ ]zones");

the, all the, all of the

}

private static String[] timezones = ZoneId.getAvailableZoneIds().toArray(new String[0]);

@Override
public boolean init(Expression<?>[] expressions, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parseResult) {
public boolean init(Expression<?>[] expressions, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) {
return true;
}

@Override
@Nullable
protected String[] get(Event event) {
return ZoneId.getAvailableZoneIds().toArray(new String[0]);
protected String @Nullable [] get(Event event) {
return timezones;
}

@Override
public boolean isSingle() {
return false;
}

@Override
public Class<? extends String> getReturnType() {
return String.class;
Expand Down
100 changes: 100 additions & 0 deletions src/main/java/ch/njol/skript/expressions/ExprDateInTimezone.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package ch.njol.skript.expressions;

import ch.njol.skript.Skript;
import ch.njol.skript.config.Node;
import ch.njol.skript.doc.Description;
import ch.njol.skript.doc.Example;
import ch.njol.skript.doc.Name;
import ch.njol.skript.doc.Since;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.ExpressionType;
import ch.njol.skript.lang.SkriptParser;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.skript.lang.util.SimpleExpression;
import ch.njol.skript.util.Date;
import ch.njol.util.Kleenean;
import org.bukkit.event.Event;
import org.jetbrains.annotations.Nullable;
import org.skriptlang.skript.log.runtime.SyntaxRuntimeErrorProducer;

import java.time.DateTimeException;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;

@Name("Date in Timezone")
@Description({
"Returns a date in the specified timezone. Note that the result date might not be equal to the input date.",
"Use <a href='#ExprAllTimezones'>all timezones</a> to get a list of valid timezones."
})
@Example("""
set {_date} to now in timezone "Europe/Istanbul"
set {_clock} to {_date} formatted as "kk:mm"
send "It is currently %{_clock}% in Istanbul!" to player
""")
@Since("INSERT VERSION")
public class ExprDateInTimezone extends SimpleExpression<Date> {

static {
Skript.registerExpression(ExprDateInTimezone.class, Date.class, ExpressionType.SIMPLE, "[the] [date] %date% in time[ ]zone %string%");
}

private Expression<Date> date;
private Expression<String> timezone;

@Override
public boolean init(Expression<?>[] expressions, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) {
date = (Expression<Date>) expressions[0];
timezone = (Expression<String>) expressions[1];
return true;
}

@Override
protected Date @Nullable [] get(Event event) {
String timezone = this.timezone.getSingle(event);
Date date = this.date.getSingle(event);

if (timezone == null) {
error("Timezone is not set.");
return new Date[0];
}

if (date == null) {
return new Date[0];
}

ZoneId targetZoneId;
try {
targetZoneId = ZoneId.of(timezone);
} catch (DateTimeException e) { // invalid zone format
error("Invalid timezone.");
return new Date[0];
}

Instant instantDate = date.toInstant();
ZoneId localZoneId = ZoneId.systemDefault();
Instant shiftedNow = ZonedDateTime.ofInstant(instantDate, targetZoneId)
.toLocalDateTime()
.atZone(localZoneId)
.toInstant();
java.util.Date javaDate = java.util.Date.from(shiftedNow);
Date shiftedDate = Date.fromJavaDate(javaDate);
return new Date[]{ shiftedDate };
}

@Override
public boolean isSingle() {
return true;
}

@Override
public Class<? extends Date> getReturnType() {
return Date.class;
}

@Override
public String toString(@Nullable Event event, boolean debug) {
return "date " + date.toString(event, debug) + " in timezone " + timezone.toString(event, debug);
}

}
59 changes: 12 additions & 47 deletions src/main/java/ch/njol/skript/expressions/ExprNow.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,74 +15,39 @@
import ch.njol.skript.util.Date;
import ch.njol.util.Kleenean;

import java.time.DateTimeException;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;

@Name("Now")
@Description("The current <a href='classes.html#date'>system time</a> of the server. Use <a href='#ExprTime'>time</a> to get the <a href='classes.html#time'>Minecraft time</a> of a world.")
@Examples({"broadcast \"Current server time: %now%\""})
@Since("1.4, INSERT VERSION (timezones)")
@Since("1.4")
public class ExprNow extends SimpleExpression<Date> {

static {
Skript.registerExpression(ExprNow.class, Date.class, ExpressionType.SIMPLE, "now [timezone:in time[ ]zone %-string%]");
Skript.registerExpression(ExprNow.class, Date.class, ExpressionType.SIMPLE, "now");
}

private boolean usingTimezone;
private Expression<String> timezone;

@Override
public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) {
usingTimezone = parseResult.hasTag("timezone");
timezone = (Expression<String>) exprs[0];
public boolean init(final Expression<?>[] exprs, final int matchedPattern, final Kleenean isDelayed, final ParseResult parseResult) {
return true;
}

@Override
protected Date[] get(Event event) {
if (usingTimezone) {
String timezone = this.timezone.getSingle(event);
if (timezone == null) {
return new Date[0];
}

ZoneId targetZoneId;
try {
targetZoneId = ZoneId.of(timezone);
} catch (DateTimeException e) { // invalid zone format
return new Date[0];
}

ZoneId localZoneId = ZoneId.systemDefault();
Instant shiftedNow = ZonedDateTime.now(targetZoneId)
.toLocalDateTime()
.atZone(localZoneId)
.toInstant();
java.util.Date javaDate = java.util.Date.from(shiftedNow);
Date date = Date.fromJavaDate(javaDate);
return new Date[]{ date };
}
return new Date[]{ new Date() };
@Override
protected Date[] get(final Event e) {
return new Date[] {new Date()};
}

@Override
public boolean isSingle() {
return true;
}

@Override
public Class<? extends Date> getReturnType() {
return Date.class;
}

@Override
public String toString(@Nullable Event e, boolean debug) {
if (usingTimezone) {
return "now in timezone " + timezone.toString(e, debug);
}
public String toString(final @Nullable Event e, final boolean debug) {
return "now";
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,7 @@ public TestResults runTests(Path runnerRoot, Path testsRoot, boolean devMode, bo
args.add("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000");
args.add("-Duser.language=en");
args.add("-Duser.country=US");
args.add("-Duser.timezone=UTC");
args.addAll(jvmArgs);
args.addAll(Arrays.asList(commandLine));

Expand Down
15 changes: 15 additions & 0 deletions src/test/skript/tests/misc/timezone.sk
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
test "timezone syntaxes":
assert size of all timezones > 0 with "timezones aren't set"

assert timezone "Europe/Istanbul" is valid with "single timezone should've been valid"
assert timezones ("Europe/Istanbul", "Asia/Tokyo") are valid with "multiple timezones should've been valid"

assert timezone "hello!" is invalid with "single timezone should've been invalid"
assert timezones ("hello!", "Asia/Tokyo") are invalid with "multiple timezones should've been invalid"

set {_d} to date(2030, 6, 4, 7, 23)
set {_d.in.nyc} to date(2030, 6, 4, 3, 23)
set {_d.in.istanbul} to date(2030, 6, 4, 10, 23)

assert difference between ({_d} in timezone "America/New_York") and {_d.in.nyc} < 1 second with "returned incorrect date for New York"
assert difference between ({_d} in timezone "Europe/Istanbul") and {_d.in.istanbul} < 1 second with "returned incorrect date for Istanbul"