Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a duration elegantly in Java 7

Tags:

java

android

To define a duration, sometimes we just write below

long thirtyMinutes = 30 * 60 * 1000; // In Miliseconds

As of Java 8 with the java.time framework, we could make it more elegant using

long thirtyMinutes = Duration.ofMinutes(30).toMillis();

But as I'm still in Java 7 (Android), I can't use java.time.Duration. So is there anyway I could have it define as elegant as Java 8, instead of just ruing the multiplication equation above?

like image 406
Elye Avatar asked Mar 07 '26 20:03

Elye


1 Answers

Without a backported library- java.util.concurrent.TimeUnit

//convert 4 hours to milliseconds    
long ms = TimeUnit.Hours.toMillis(4);  

Similar for minutes, days, etc.

like image 55
Gabe Sechan Avatar answered Mar 09 '26 10:03

Gabe Sechan