Code Patterns

Copy-paste examples for common plugin tasks. Commands, events, ECS, GUI, and more.

← Back to Patterns
util

Duration Parser

Parse human-readable duration strings like "1d 2h 30m 15s" into milliseconds

Example Code

java
public class DurationParser {
    public static HashMap<String, Long> DURATIONS = new HashMap<>();

    static {
        DURATIONS.put("d", 86400L);  // days
        DURATIONS.put("h", 3600L);   // hours
        DURATIONS.put("m", 60L);     // minutes
        DURATIONS.put("s", 1L);      // seconds
    }

    /**
     * Returns time in milliseconds
     */
    public static long parse(String duration) {
        var split = duration.split(" ");
        var time = 0L;
        for (var s : split) {
            for (String unit : DURATIONS.keySet()) {
                if (s.endsWith(unit)) {
                    time += Long.parseLong(s.replace(unit, "")) * DURATIONS.get(unit);
                    break;
                }
            }
        }
        return time * 1000L;
    }
}