I want to have an API that looks like
public static long toMillis ( long duration, ChronoUnit unit ) { // magic duration to millis } toMillis( 5, ChronoUnit.SECONDS); // 5000
of course I'm not actually writing toMillis
but that's essentially what I'm trying to do.
A simple solution is to get the timedelta object by finding the difference of the given datetime with Epoch time, i.e., midnight 1 January 1970. To obtain time in milliseconds, you can use the timedelta. total_seconds() * 1000 .
To convert milliseconds to hours and minutes: Divide the milliseconds by 1000 to get the seconds. Divide the seconds by 60 to get the minutes. Divide the minutes by 60 to get the hours.
If TimeUnit or toMinutes are unsupported (such as on Android before API version 9), use the following equations: int seconds = (int) (milliseconds / 1000) % 60 ; int minutes = (int) ((milliseconds / (1000*60)) % 60); int hours = (int) ((milliseconds / (1000*60*60)) % 24); //etc...
You can use Duration
for this:
Duration.of(5, ChronoUnit.SECONDS).toMillis()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With