ch.njol.skript.util.Date Java Examples

The following examples show how to use ch.njol.skript.util.Date. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExprCmdCooldownInfo.java    From Skript with GNU General Public License v3.0 6 votes vote down vote up
@Nullable
@Override
public Class<?>[] acceptChange(Changer.ChangeMode mode) {
	switch (mode) {
		case ADD:
		case REMOVE:
			if (pattern <= 1)
				// remaining or elapsed time
				return new Class<?>[] { Timespan.class };
		case RESET:
		case SET:
			if (pattern <= 1)
				// remaining or elapsed time
				return new Class<?>[] { Timespan.class };
			else if (pattern == 3)
				// last usage date
				return new Class<?>[] { Date.class };
	}
	return null;
}
 
Example #2
Source File: Reg.java    From skUtilities with GNU General Public License v3.0 5 votes vote down vote up
static void convert() {
  Skript.registerExpression(ExprToBin.class, String.class, ExpressionType.PROPERTY, "[skutil[ities] ]convert (0¦(text|string)|1¦decimal|2¦hexa[decimal]|3¦octal) %string% to bin[ary]", "[skutil[ities] ](0¦(text|string)|1¦decimal|2¦hexa[decimal]|3¦octal) %string% as bin[ary]");
  Skript.registerExpression(ExprToAscii.class, String.class, ExpressionType.PROPERTY, "[skutil[ities] ]convert ascii %numbers% to (0¦(text|string)|1¦unicode)", "[skutil[ities] ]ascii %numbers% as (0¦(text|string)|1¦unicode)");

  Skript.registerExpression(ExprFromString.class, String.class, ExpressionType.PROPERTY, "[skutil[ities] ]convert (text|string) %string% to (0¦ascii|1¦unicode)", "[skutil[ities] ](text|string) %string% as (0¦ascii|1¦unicode)");
  Skript.registerExpression(ExprFromBin.class, String.class, ExpressionType.PROPERTY, "[skutil[ities] ]convert bin[ary] %string% to (0¦(text|string)|1¦decimal|2¦hexa[decimal]|3¦octal)", "[skutil[ities] ]bin[ary] %string% as (0¦(text|string)|1¦decimal|2¦hexa[decimal]|3¦octal)");
  Skript.registerExpression(ExprFromUnicode.class, String.class, ExpressionType.PROPERTY, "[skutil[ities] ]convert unicode %string% to (0¦(text|string)|1¦ascii)", "[skutil[ities] ]unicode %string% as (0¦(text|string)|1¦ascii)");

  Skript.registerExpression(ExprHexaToNum.class, Number.class, ExpressionType.PROPERTY, "[skutil[ities] ]convert hexa[decimal] %string% to num[ber]", "[skutil[ities] ]hexa[decimal] %string% as num[ber]");
  Skript.registerExpression(ExprNumToHexa.class, String.class, ExpressionType.PROPERTY, "convert num[ber] %number% to hexa[decimal]", "[skutil[ities] ]num[ber] %number% as hexa[decimal]");

  Skript.registerExpression(ExprHexToRgb.class, String.class, ExpressionType.PROPERTY, "[skutil[ities] ]convert hex %string% to rgb",  "[skutil[ities] ]hex %string% as rgb");
  Skript.registerExpression(ExprRgbToHex.class, String.class, ExpressionType.PROPERTY, "[skutil[ities] ]convert rgb %number%, %number%, %number% to hex", "[skutil[ities] ]rgb %number%, %number%, %number% as hex");

  Skript.registerExpression(ExprDateParsed.class, Date.class, ExpressionType.PROPERTY, "[skutil[ities] ]%string% parsed as date[ formatted as %-string%]");
  Skript.registerExpression(ExprDateToUnix.class, Number.class, ExpressionType.PROPERTY, "[skutil[ities] ]convert date %date% to unix[ date]", "[skutil[ities] ]date %date% as unix[ date]");
  Skript.registerExpression(ExprUnixToDate.class, Date.class, ExpressionType.PROPERTY, "[skutil[ities] ]convert unix[ date] %number% to date", "[skutil[ities] ]unix[ date] %number% as date");
  Skript.registerExpression(ExprUnixToFormattedDate.class, String.class, ExpressionType.PROPERTY, "[skutil[ities] ]convert unix[ date] %number% to date formatted as %string%", "[skutil[ities] ]unix[ date] %number% as date formatted as %string%");

  Skript.registerExpression(ExprBase64.class, String.class, ExpressionType.PROPERTY, "[skutil[ities] ](0¦en|1¦de)code base[ ]64 %string%");
  Skript.registerExpression(ExprMorse.class, String.class, ExpressionType.PROPERTY, "[skutil[ities] ](0¦en|1¦de)code morse[ code] %string%");
  Skript.registerExpression(ExprEncrypt.class, String.class, ExpressionType.PROPERTY, "[skutil[ities] ](0¦en|1¦de)crypt %string% using %-string% with key %-string%");

  Skript.registerExpression(ExprClearAccented.class, String.class, ExpressionType.PROPERTY, "[skutil[ities] ]clear accented chars from %string%");
  Skript.registerExpression(ExprHash.class, String.class, ExpressionType.PROPERTY, "[skutil[ities] ]hash[ed] %string% using %-string%");
  Skript.registerExpression(ExprMirrorTxt.class, String.class, ExpressionType.PROPERTY, "[skutil[ities] ](mirror[ed]|flip[ped]|reverse[d]) %string%");

  Skript.registerExpression(ExprToUpperLower.class, String.class, ExpressionType.PROPERTY, "[skutil[ities] ]convert (text|string) %string% to (0¦uppercase|1¦lowercase)");
  Skript.registerExpression(ExprRandomizeString.class, String.class, ExpressionType.PROPERTY, "[skutil[ities] ]randomize %string%");
}
 
Example #3
Source File: CondDate.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "null"})
@Override
public boolean init(final Expression<?>[] exprs, final int matchedPattern, final Kleenean isDelayed, final ParseResult parseResult) {
	date = (Expression<Date>) exprs[0];
	delta = (Expression<Timespan>) exprs[1];
	setNegated(matchedPattern == 1);
	return true;
}
 
Example #4
Source File: ExprDateAgoLater.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
@Override
protected Date[] get(Event e) {
    Timespan timespan = this.timespan.getSingle(e);
    Date date = this.date == null ? new Date() : this.date.getSingle(e);
    if (timespan == null || date == null) {
        return null;
    }
    if (ago) {
        date.subtract(timespan);
    } else {
        date.add(timespan);
    }
    return new Date[]{date};
}
 
Example #5
Source File: ExprDateInner.java    From skUtilities with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public boolean init(Expression<?>[] e, int i, Kleenean k, ParseResult p) {
  id = (Expression<Date>) e[0];
  ty = p.mark;
  return true;
}
 
Example #6
Source File: ExprDateAgoLater.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "null"})
@Override
public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parseResult) {
    timespan = (Expression<Timespan>) exprs[0];
    date = (Expression<Date>) exprs[1];
    ago = matchedPattern == 0;
    return true;
}
 
Example #7
Source File: ScriptCommand.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
public void setLastUsage(UUID uuid, Event event, @Nullable Date date) {
	if (cooldownStorage != null) {
		// Using a variable
		String name = getStorageVariableName(event);
		assert name != null;
		Variables.setVariable(name, date, null, false);
	} else {
		// Use the map
		if (date == null)
			lastUsageMap.remove(uuid);
		else
			lastUsageMap.put(uuid, date);
	}
}
 
Example #8
Source File: ExprDateParsed.java    From skUtilities with GNU General Public License v3.0 5 votes vote down vote up
@Override
@Nullable
protected Date[] get(Event e) {
  String s = id.getSingle(e);
  try {
    String ddf = new SimpleDateFormat().toPattern();
    if (format != null) ddf = format.getSingle(e);
    LocalDateTime ldt = LocalDateTime.parse(s, DateTimeFormatter.ofPattern(ddf));
    return new Date[]{new Date((ldt.toEpochSecond(ZoneOffset.ofTotalSeconds(ldt.getSecond())) + ldt.getSecond()) * 1000)};
  } catch (Exception x) {
    skUtilities.prSysE(x.getMessage(), getClass().getSimpleName(), x);
  }
  return null;
}
 
Example #9
Source File: ExprFormatTime.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected String[] get(Event e, Date[] source) {
	return get(source, new Getter<String, Date>() {
		@Override
		public String get(Date date) {
			return format.format(new java.util.Date(date.getTimestamp()));
		}
	});
}
 
Example #10
Source File: ScriptCommand.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
public Date getLastUsage(UUID uuid, Event event) {
	if (cooldownStorage == null) {
		return lastUsageMap.get(uuid);
	} else {
		String name = getStorageVariableName(event);
		assert name != null;
		return (Date) Variables.getVariable(name, null, false);
	}
}
 
Example #11
Source File: ExprUnixToDate.java    From skUtilities with GNU General Public License v3.0 5 votes vote down vote up
@Override
@Nullable
protected Date[] get(Event e) {
  try {
    String si = n.getSingle(e).toString();
    if (!(si.length() == 10)) {
      si = si.substring(0, 10);
    }
    return new Date[]{new Date(Integer.parseInt(si) * 1000L)};
  } catch (Exception x) {
    skUtilities.prSysE(x.getMessage(), getClass().getSimpleName(), x);
  }
  return null;
}
 
Example #12
Source File: ExprCmdCooldownInfo.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
@Override
@Nullable
protected Object[] get(Event e) {
	if (!(e instanceof ScriptCommandEvent))
		return null;
	ScriptCommandEvent event = ((ScriptCommandEvent) e);
	ScriptCommand scriptCommand = event.getSkriptCommand();
	
	CommandSender sender = event.getSender();
	if (scriptCommand.getCooldown() == null || !(sender instanceof Player))
		return null;
	Player player = (Player) event.getSender();
	UUID uuid = player.getUniqueId();
	
	switch (pattern) {
		case 0:
		case 1:
			long ms = pattern != 1
					? scriptCommand.getRemainingMilliseconds(uuid, event)
					: scriptCommand.getElapsedMilliseconds(uuid, event);
			return new Timespan[] { new Timespan(ms) };
		case 2:
			return new Timespan[] { scriptCommand.getCooldown() };
		case 3:
			return new Date[] { scriptCommand.getLastUsage(uuid, event) };
		case 4:
			return new String[] { scriptCommand.getCooldownBypass() };
	}
	
	return null;
}
 
Example #13
Source File: ClassesTest.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void test() {
	final Object[] random = {
			// Java
			(byte) 127, (short) 2000, -1600000, 1L << 40, -1.5f, 13.37,
			"String",
			
			// Skript
			SkriptColor.BLACK, StructureType.RED_MUSHROOM, WeatherType.THUNDER,
			new Date(System.currentTimeMillis()), new Timespan(1337), new Time(12000), new Timeperiod(1000, 23000),
			new Experience(15), new Direction(0, Math.PI, 10), new Direction(new double[] {0, 1, 0}),
			new EntityType(new SimpleEntityData(HumanEntity.class), 300),
			new CreeperData(),
			new SimpleEntityData(Snowball.class),
			new HorseData(Variant.SKELETON_HORSE),
			new WolfData(),
			new XpOrbData(50),
			
			// Bukkit - simple classes only
			GameMode.ADVENTURE, InventoryType.CHEST, DamageCause.FALL,
			
			// there is also at least one variable for each class on my test server which are tested whenever the server shuts down.
	};
	
	for (final Object o : random) {
		Classes.serialize(o); // includes a deserialisation test
	}
}
 
Example #14
Source File: SkriptYamlRepresenter.java    From skript-yaml with MIT License 5 votes vote down vote up
public SkriptYamlRepresenter() {
	this.nullRepresenter = new Represent() {
		@Override
		public Node representData(Object o) {
			return representScalar(Tag.NULL, "");
		}
	};

	this.representers.put(SkriptClass.class, new RepresentSkriptClass());
	this.representers.put(ItemType.class, new RepresentSkriptItemType());
	this.representers.put(Slot.class, new RepresentSkriptSlot());
	this.representers.put(Date.class, new RepresentSkriptDate());
	this.representers.put(Time.class, new RepresentSkriptTime());
	this.representers.put(Timespan.class, new RepresentSkriptTimespan());
	this.representers.put(Color.class, new RepresentSkriptColor());
	this.representers.put(WeatherType.class, new RepresentSkriptWeather());

	this.representers.put(Vector.class, new RepresentVector());
	this.representers.put(Location.class, new RepresentLocation());

	this.multiRepresenters.put(ConfigurationSerializable.class, new RepresentConfigurationSerializable());

	for (Class<?> c : representers.keySet()) {
		if (c != null) {
			String name = c.getSimpleName();
			if (!representedClasses.contains(name))
				representedClasses.add(name);
		}
	}
}
 
Example #15
Source File: ScriptCommand.java    From Skript with GNU General Public License v3.0 4 votes vote down vote up
public void setElapsedMilliSeconds(UUID uuid, Event event, long milliseconds) {
	Date date = new Date();
	date.subtract(new Timespan(milliseconds));
	setLastUsage(uuid, event, date);
}
 
Example #16
Source File: DefaultComparators.java    From Skript with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Relation compare(final Date d1, final Date d2) {
	return Relation.get(d1.compareTo(d2));
}
 
Example #17
Source File: ExprDateToUnix.java    From skUtilities with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public boolean init(Expression<?>[] e, int i, Kleenean k, ParseResult p) {
  id = (Expression<Date>) e[0];
  return true;
}
 
Example #18
Source File: ExprUnixToDate.java    From skUtilities with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Class<? extends Date> getReturnType() {
  return Date.class;
}
 
Example #19
Source File: ExprDateParsed.java    From skUtilities with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Class<? extends Date> getReturnType() {
  return Date.class;
}
 
Example #20
Source File: ExprDateInner.java    From skUtilities with GNU General Public License v3.0 4 votes vote down vote up
@Override
@Nullable
protected String[] get(Event e) {
  Date d = new Date(id.getSingle(e).getTimestamp() * 1000L);
  try {
    LocalDateTime ldt = LocalDateTime.parse(d.toString(), DateTimeFormatter.ofPattern(new SimpleDateFormat().toPattern()));
    switch (ty) {
      case 0: {
        return new String[]{String.valueOf(ldt.getYear())};
      } case 1: {
        return new String[]{String.valueOf(ldt.getMonthValue())};
      } case 2: {
        return new String[]{ldt.getMonth().name()};
      } case 3: {
        return new String[]{String.valueOf(ldt.getDayOfYear())};
      } case 4: {
        return new String[]{String.valueOf(ldt.getDayOfMonth())};
      } case 5: {
        return new String[]{String.valueOf(ldt.getDayOfWeek().getValue())};
      } case 6: {
        return new String[]{ldt.getDayOfWeek().name()};
      } case 7: {
        return new String[]{String.valueOf(ldt.getHour())};
      } case 8: {
        return new String[]{String.valueOf(ldt.getMinute())};
      } case 9: {
        long ul = (id.getSingle(e).getTimestamp() / 1000L) - (ldt.toEpochSecond(ZoneOffset.ofTotalSeconds(ldt.getSecond())));
        while (ul > 59) {
          if (ul > 3600) {
            ul = (ul - 3600);
          } else {
            ul = (ul - 900);
          }
        }
        return new String[]{String.valueOf(ul)};
      }
    }
  } catch (Exception x) {
    skUtilities.prSysE(x.getMessage(), getClass().getSimpleName(), x);
  }
  return null;
}
 
Example #21
Source File: ScriptCommand.java    From Skript with GNU General Public License v3.0 4 votes vote down vote up
public long getElapsedMilliseconds(UUID uuid, Event event) {
	Date lastUsage = getLastUsage(uuid, event);
	return lastUsage == null ? 0 : new Date().getTimestamp() - lastUsage.getTimestamp();
}
 
Example #22
Source File: ScriptCommand.java    From Skript with GNU General Public License v3.0 4 votes vote down vote up
public boolean execute(final CommandSender sender, final String commandLabel, final String rest) {
	if (sender instanceof Player) {
		if ((executableBy & PLAYERS) == 0) {
			sender.sendMessage("" + m_executable_by_console);
			return false;
		}
	} else {
		if ((executableBy & CONSOLE) == 0) {
			sender.sendMessage("" + m_executable_by_players);
			return false;
		}
	}

	final ScriptCommandEvent event = new ScriptCommandEvent(ScriptCommand.this, sender);

	if (!permission.isEmpty() && !sender.hasPermission(permission)) {
		if (sender instanceof Player) {
			List<MessageComponent> components =
					permissionMessage.getMessageComponents(event);
			((Player) sender).spigot().sendMessage(BungeeConverter.convert(components));
		} else {
			sender.sendMessage(permissionMessage.getSingle(event));
		}
		return false;
	}

	cooldownCheck : {
		if (sender instanceof Player && cooldown != null) {
			Player player = ((Player) sender);
			UUID uuid = player.getUniqueId();

			// Cooldown bypass
			if (!cooldownBypass.isEmpty() && player.hasPermission(cooldownBypass)) {
				setLastUsage(uuid, event, null);
				break cooldownCheck;
			}

			if (getLastUsage(uuid, event) != null) {
				if (getRemainingMilliseconds(uuid, event) <= 0) {
					if (!SkriptConfig.keepLastUsageDates.value())
						setLastUsage(uuid, event, null);
				} else {
					String msg = cooldownMessage.getSingle(event);
					if (msg != null)
						sender.sendMessage(msg);
					return false;
				}
			}
		}
	}

	if (Bukkit.isPrimaryThread()) {
		execute2(event, sender, commandLabel, rest);
		if (sender instanceof Player && !event.isCooldownCancelled())
			setLastUsage(((Player) sender).getUniqueId(), event, new Date());
	} else {
		// must not wait for the command to complete as some plugins call commands in such a way that the server will deadlock
		Bukkit.getScheduler().scheduleSyncDelayedTask(Skript.getInstance(), new Runnable() {
			@Override
			public void run() {
				execute2(event, sender, commandLabel, rest);
				if (sender instanceof Player && !event.isCooldownCancelled())
					setLastUsage(((Player) sender).getUniqueId(), event, new Date());
			}
		});
	}

	return true; // Skript prints its own error message anyway
}
 
Example #23
Source File: ExprCmdCooldownInfo.java    From Skript with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Class<?> getReturnType() {
	if (pattern <= 2)
		return Timespan.class;
	return pattern == 3 ? Date.class : String.class;
}
 
Example #24
Source File: ExprNow.java    From Skript with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Class<? extends Date> getReturnType() {
	return Date.class;
}
 
Example #25
Source File: ExprNow.java    From Skript with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected Date[] get(final Event e) {
	return new Date[] {new Date()};
}
 
Example #26
Source File: ExprUnixTicks.java    From Skript with GNU General Public License v3.0 4 votes vote down vote up
@Override
@Nullable
public Number convert(Date f) {
	return f.getTimestamp() / 1000.0;
}
 
Example #27
Source File: ExprUnixDate.java    From Skript with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Class<? extends Date> getReturnType() {
	return Date.class;
}
 
Example #28
Source File: ExprUnixDate.java    From Skript with GNU General Public License v3.0 4 votes vote down vote up
@Override
@Nullable
public Date convert(Number n) {
	return new Date((long)(n.doubleValue() * 1000));
}
 
Example #29
Source File: ExprDateAgoLater.java    From Skript with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Class<? extends Date> getReturnType() {
    return Date.class;
}
 
Example #30
Source File: SkriptYamlRepresenter.java    From skript-yaml with MIT License 4 votes vote down vote up
@Override
public Node representData(Object data) {
	Calendar calendar = Calendar.getInstance(getTimeZone() == null ? TimeZone.getTimeZone("UTC") : timeZone);
	calendar.setTime(new java.util.Date(((Date) data).getTimestamp()));

	int years = calendar.get(Calendar.YEAR);
	int months = calendar.get(Calendar.MONTH) + 1; // 0..12
	int days = calendar.get(Calendar.DAY_OF_MONTH); // 1..31
	int hour24 = calendar.get(Calendar.HOUR_OF_DAY); // 0..24
	int minutes = calendar.get(Calendar.MINUTE); // 0..59
	int seconds = calendar.get(Calendar.SECOND); // 0..59
	int millis = calendar.get(Calendar.MILLISECOND);
	StringBuilder buffer = new StringBuilder(String.valueOf(years));
	while (buffer.length() < 4) {
		// ancient years
		buffer.insert(0, "0");
	}
	buffer.append("-");
	if (months < 10) {
		buffer.append("0");
	}
	buffer.append(String.valueOf(months));
	buffer.append("-");
	if (days < 10) {
		buffer.append("0");
	}
	buffer.append(String.valueOf(days));
	buffer.append("T");
	if (hour24 < 10) {
		buffer.append("0");
	}
	buffer.append(String.valueOf(hour24));
	buffer.append(":");
	if (minutes < 10) {
		buffer.append("0");
	}
	buffer.append(String.valueOf(minutes));
	buffer.append(":");
	if (seconds < 10) {
		buffer.append("0");
	}
	buffer.append(String.valueOf(seconds));
	if (millis > 0) {
		if (millis < 10) {
			buffer.append(".00");
		} else if (millis < 100) {
			buffer.append(".0");
		} else {
			buffer.append(".");
		}
		buffer.append(String.valueOf(millis));
	}

	// Get the offset from GMT taking DST into account
	int gmtOffset = calendar.getTimeZone().getOffset(calendar.get(Calendar.ERA), calendar.get(Calendar.YEAR),
			calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH),
			calendar.get(Calendar.DAY_OF_WEEK), calendar.get(Calendar.MILLISECOND));
	if (gmtOffset == 0) {
		buffer.append('Z');
	} else {
		if (gmtOffset < 0) {
			buffer.append('-');
			gmtOffset *= -1;
		} else {
			buffer.append('+');
		}
		int minutesOffset = gmtOffset / (60 * 1000);
		int hoursOffset = minutesOffset / 60;
		int partOfHour = minutesOffset % 60;

		if (hoursOffset < 10) {
			buffer.append('0');
		}
		buffer.append(hoursOffset);
		buffer.append(':');
		if (partOfHour < 10) {
			buffer.append('0');
		}
		buffer.append(partOfHour);
	}

	return representScalar(new Tag("!skriptdate"), buffer.toString());
}