Skip to content

TimeUtils

Fulminazzo edited this page Oct 2, 2023 · 1 revision

Many times, while working with commands and timers, it will happen that you may want to display the remaining time for a certain task. While this can be trivial, it can also get really repetitive and annoying, especially if working on different projects at once.
BearCommands provides TimeUtils, a utility class created to automate the conversion of time into strings. More specifically, it allows to convert a long, representing the seconds, into an ordinated and corrected string:

public class TimeUtils {

    /**
     * Parses the given time as a string.
     * @param timeInSeconds: the time;
     * @param timeFormat: the format with which parse the time. Supports %time% and %time-unit% as placeholders;
     * @param splitter: the splitter to be used between two time units (for example a comma);
     * @param seconds: the word to be used as seconds (plural);
     * @param second: the word to be used as second (singular);
     * @param minutes: the word to be used as minutes (plural);
     * @param minute: the word to be used as minute (singular);
     * @param hours: the word to be used as hours (plural);
     * @param hour: the word to be used as hour (singular);
     * @param days: the word to be used as days (plural);
     * @param day: the word to be used as day (singular);
     * @param months: the word to be used as months (plural);
     * @param month: the word to be used as month (singular);
     * @param years: the word to be used as years (plural);
     * @param year: the word to be used as year (singular).
     * @return the formatted time as string.
     */
    public static String parseTime(long timeInSeconds, String timeFormat, String splitter,
                                   String seconds, String second,
                                   String minutes, String minute,
                                   String hours, String hour,
                                   String days, String day,
                                   String months, String month,
                                   String years, String year);
}

Seeing all these parameters might seem intimidating, but the usage of this function is very simple! Just do keep in mind that all the strings are basically replacements for any placeholder encountered.
So for example, an implementation like this:

long time = 3724;
// NOTE: colors with ampersand (&) are supported!
String message = TimeUtils.parseTime(time, "%time% %time-unit%", ", ",
        "seconds", "second", "minutes", "minute", "hours", "hour",
        "days", "day", "months", "month", "years", "year");
player.sendMessage(message);

will send the player the following message: 1 hour, 2 minutes, 4 seconds.