Created
May 6, 2021 06:26
-
-
Save Magnum97/ac40c1da59e79e0478d9d86340ec526e to your computer and use it in GitHub Desktop.
This file contains 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
import lombok.experimental.UtilityClass; | |
import java.time.Instant; | |
import java.time.LocalDateTime; | |
import java.time.ZoneOffset; | |
import java.time.format.DateTimeFormatter; | |
import java.time.format.DateTimeFormatterBuilder; | |
import java.time.format.DateTimeParseException; | |
import java.time.temporal.ChronoField; | |
import java.time.temporal.ChronoUnit; | |
import java.util.StringJoiner; | |
@UtilityClass | |
public class TimeUtil { | |
public final ZoneOffset ZONE = ZoneOffset.UTC; | |
public DateTimeFormatter f = new DateTimeFormatterBuilder().appendPattern("[dd'd':]HH'h':mm'm':ss's'") | |
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1).parseDefaulting(ChronoField.MONTH_OF_YEAR, 1) | |
.parseDefaulting(ChronoField.YEAR, 1970).toFormatter(); | |
private final ChronoUnit[] units = { ChronoUnit.DAYS, ChronoUnit.HOURS, ChronoUnit.MINUTES, ChronoUnit.SECONDS }; | |
private LocalDateTime fromMillis(long millis) { | |
return Instant.ofEpochMilli(millis).atZone(ZONE).toLocalDateTime(); | |
} | |
private String fix(String toFix) { | |
String d = "00d"; | |
String h = "00h"; | |
String m = "00m"; | |
String s = "00s"; | |
String[] a = toFix.split(":"); | |
for (String st : a) { | |
if (st.length() == 2) | |
st = "0" + st; | |
if (st.contains("d")) | |
d = st; | |
if (st.contains("h")) | |
h = st; | |
if (st.contains("m")) | |
m = st; | |
if (st.contains("s")) | |
s = st; | |
} | |
StringJoiner j = new StringJoiner(":"); | |
j.add(d); | |
j.add(h); | |
j.add(m); | |
j.add(s); | |
return j.toString(); | |
} | |
public String millisToString(long targetMilli) { | |
LocalDateTime past = fromMillis(0); | |
LocalDateTime future = fromMillis(targetMilli); | |
Object[] times = new Long[units.length]; | |
for (int i = 0; i < units.length; i++) { | |
long time = past.until(future, units[i]); | |
past = past.plus((Long) (times[i] = time), units[i]); | |
} | |
return String.format("&a%d&7d &a%d&7h &a%d&7m &a%d&7s", times); | |
} | |
public long stringToMillis(String input) { | |
if (input == null || input.isEmpty()) | |
return -1; | |
input = fix(input); | |
boolean zero = input.startsWith("00"); | |
try { | |
return LocalDateTime.parse(zero ? input.substring(4) : input, f).plusDays(zero ? 0 : 1).toInstant(ZONE) | |
.toEpochMilli(); | |
} catch (DateTimeParseException e) { | |
return -1; | |
} | |
} | |
public int getDifference(long targetMilli, ChronoUnit unit) { | |
return (int) unit.between(fromMillis(targetMilli), fromMillis(System.currentTimeMillis())); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment