Last active
March 12, 2016 22:56
-
-
Save DarkSeraphim/fad394330b3b720f0d6c to your computer and use it in GitHub Desktop.
Converting longs to nice time Strings and back
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public enum TimeUnit | |
| { | |
| S("second", 1000, 's'), | |
| MIN("minute", 60000, 'm'), | |
| HOUR("hour", 3600000, 'h'), | |
| DAY("day", 86400000, 'd'), | |
| WEEK("week", 604800000, 'w') | |
| ; | |
| private final String name; | |
| private final long ms; | |
| private final char unit; | |
| private static final Map<Character, Long> convertion = new HashMap<Character, Long>(); | |
| private static final TimeUnit[] order = new TimeUnit[]{WEEK, DAY, HOUR, MIN, S}; | |
| private static final Pattern isLong = Pattern.compile("[0-9]+"); | |
| private TimeUnit(String name, long ms, char unit) | |
| { | |
| this.name = name; | |
| this.ms = ms; | |
| this.unit = unit; | |
| } | |
| static | |
| { | |
| for(TimeUnit unit : values()) | |
| convertion.put(unit.unit, unit.ms); | |
| } | |
| public String toString(int x) | |
| { | |
| String r = this.name; | |
| if(x > 1) | |
| r += "s"; | |
| return x+" "+r; | |
| } | |
| private static long convert(char c) | |
| { | |
| return convertion.getOrDefault(c, 0); | |
| } | |
| public static String toString(long time) | |
| { | |
| StringBuilder sb = new StringBuilder(); | |
| int t; | |
| for(TimeUnit unit : order) | |
| { | |
| if(time > unit.ms) | |
| { | |
| t = (int) Math.floor((double)time / (double)unit.ms); | |
| sb.append(unit.toString(t)).append(" "); | |
| time -= t * unit.ms; | |
| } | |
| } | |
| return sb.toString().trim(); | |
| } | |
| public static long toLong(String s) | |
| { | |
| long cooldown = 0; | |
| String[] time = s.split(" "); | |
| for(String t : time) | |
| { | |
| char c = t.charAt(t.length() - 1); | |
| t = t.substring(0, t.length() - 1); | |
| if(!isLong.matcher(t).matches()) | |
| continue; | |
| cooldown += Long.parseLong(t) * TimeUnit.convert(c); | |
| } | |
| return cooldown; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment