Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert "duration" "Unit" to milliseconds

Tags:

java

java-time

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.

like image 358
xenoterracide Avatar asked Jun 08 '16 22:06

xenoterracide


People also ask

How do you convert datetime to milliseconds?

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 .

How do you convert milliseconds to hours and minutes?

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.

How do you convert milliseconds to hours in Java?

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...


Video Answer


1 Answers

You can use Duration for this:

Duration.of(5, ChronoUnit.SECONDS).toMillis() 
like image 57
Andrew Rueckert Avatar answered Sep 30 '22 11:09

Andrew Rueckert