package net.knarcraft.dynmapcitizens.util; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import static net.knarcraft.dynmapcitizens.formatting.StringFormatter.replacePlaceholder; /** * A helper class for time formatting */ public class TimeFormatter { /** * Gets a datetime string for the given timestamp * * @param timestamp

A timestamp in milliseconds

* @return

A datetime string

*/ public static String formatTimestamp(long timestamp) { DateFormat format = new SimpleDateFormat("dd MM yyyy HH:mm:ss"); Date date = new Date(timestamp); return format.format(date); } /** * Gets the string used for displaying this sign's duration * * @return

The string used for displaying this sign's duration

*/ public static String getDurationString(long duration) { if (duration == 0) { return "immediately"; } else { double minute = 60; double hour = minute * 60; double day = hour * 24; double week = day * 7; double month = day * 30; double year = day * 365; double decade = year * 10; Map timeUnits = new HashMap<>(); timeUnits.put(decade, new String[]{"decade", "decades"}); timeUnits.put(year, new String[]{"year", "years"}); timeUnits.put(month, new String[]{"month", "months"}); timeUnits.put(week, new String[]{"week", "weeks"}); timeUnits.put(day, new String[]{"day", "days"}); timeUnits.put(hour, new String[]{"hour", "hours"}); timeUnits.put(minute, new String[]{"minute", "minutes"}); timeUnits.put(1D, new String[]{"second", "seconds"}); List sortedUnits = new ArrayList<>(timeUnits.keySet()); Collections.sort(sortedUnits); Collections.reverse(sortedUnits); for (Double unit : sortedUnits) { if (duration / unit >= 1) { double units = round(duration / unit); return formatDurationString(units, timeUnits.get(unit)[units == 1 ? 0 : 1], (units * 10) % 10 == 0); } } return formatDurationString(duration, "seconds", false); } } /** * Rounds a number to its last two digits * * @param number

The number to round

* @return

The rounded number

*/ private static double round(double number) { return Math.round(number * 100.0) / 100.0; } /** * Formats a duration string * * @param duration

The duration to display

* @param translatableMessage

The time unit to display

* @param castToInt

Whether to cast the duration to an int

* @return

The formatted duration string

*/ private static String formatDurationString(double duration, String translatableMessage, boolean castToInt) { String durationFormat = "{duration} {unit}"; durationFormat = replacePlaceholder(durationFormat, "{unit}", translatableMessage); return replacePlaceholder(durationFormat, "{duration}", castToInt ? String.valueOf((int) duration) : String.valueOf(duration)); } }