Last active
February 29, 2024 02:09
-
-
Save AngryCarrot789/1c3e1a5e4608a0b201301a14c6757ffb to your computer and use it in GitHub Desktop.
A utility class for converting between time units and ticks (e.g days in ticks, ticks to hours, etc)
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
package reghzy.api.utils; | |
import java.util.concurrent.TimeUnit; | |
public class TickUnit { | |
private static final double C1d = 50000000.0d; | |
private static final double C2d = 50000.0d; | |
private static final double C3d = 50.0d; | |
private static final double C4d = 20.0d; | |
private static final double C5d = 1200.0d; | |
private static final double C6d = 72000.0d; | |
private static final double C7d = 86400.0d; | |
/** | |
* Converts the given number of ticks into nanoseconds | |
*/ | |
public static double toNanos(long ticks) { return ticks * C1d; } | |
/** | |
* Converts the given number of ticks into microseconds | |
*/ | |
public static double toMicros(long ticks) { return ticks * C2d; } | |
/** | |
* Converts the given number of ticks into milliseconds | |
*/ | |
public static double toMillis(long ticks) { return ticks * C3d; } | |
/** | |
* Converts the given number of ticks into seconds | |
*/ | |
public static double toSeconds(long ticks) { return ticks / C4d; } | |
/** | |
* Converts the given number of ticks into minutes | |
*/ | |
public static double toMinutes(long ticks) { return ticks / C5d; } | |
/** | |
* Converts the given number of ticks into hours | |
*/ | |
public static double toHours(long ticks) { return ticks / C6d; } | |
/** | |
* Converts the given number of ticks into days | |
*/ | |
public static double toDays(long ticks) { return ticks / C7d; } | |
/** | |
* Converts the given value (in the unit of the given unit, e.g 30 seconds) into ticks | |
*/ | |
public static long toTicks(double source, TimeUnit sourceUnit) { | |
switch (sourceUnit) { | |
case NANOSECONDS: | |
return (long) (source / C1d); | |
case MICROSECONDS: | |
return (long) (source / C2d); | |
case MILLISECONDS: | |
return (long) (source / C3d); | |
case SECONDS: | |
return (long) (source * C4d); | |
case MINUTES: | |
return (long) (source * C5d); | |
case HOURS: | |
return (long) (source * C6d); | |
case DAYS: | |
return (long) (source * C7d); | |
default: | |
throw new IllegalStateException("Unexpected value: " + sourceUnit); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment