You can use Duration for this:
Duration.of(5, ChronoUnit.SECONDS).toMillis()
Answer from Andrew Rueckert on Stack OverflowYou could model your class after a well-known and tested class: java.time.LocalDate, which provides the plus(long, TemporalUnit) method.
Similarly, you could create a someMethod(long, TimeUnit) method that allows callers to pass in arbitrary amounts of any TimeUnit.
void someMethod(long amount, TimeUnit unit) {
this.longValue = unit.toMillis(amount);
}
Note that LocalDate also provides specialized methods for adding certain common units of time, like plusDays(). That gives the caller the ability to decide which is clearer for the code they're writing:
LocalDate tomorrow = today.plusDays(1);
LocalDate tomorrow = today.plus(1, TimeUnit.DAYS);
It seems to me that you don’t need to develop your own class; that you’ll be reinventing the wheel. I suggest you use the Duration class.
To convert from some time unit to a Duration:
System.out.println(Duration.of(3, ChronoUnit.HOURS));
Or alternatively:
System.out.println(Duration.ofHours(3));
Output is the same in both cases:
PT3H
It prints a little funny; this means a span of time of 3 hours. The format is ISO 8601.
System.out.println(Duration.of(2, ChronoUnit.DAYS));
PT48H
48 hours; that’s correct.
System.out.println(Duration.of(327864523, ChronoUnit.MICROS));
PT5M27.864523S
A span of 5 minutes 27.864523 seconds.
If you need to convert to milliseconds, the method is built in:
Duration dur = Duration.of(284, ChronoUnit.MINUTES);
System.out.println("" + dur.toMillis() + " milliseconds");
17040000 milliseconds
Duration is part of java.time, the modern Java date and time API, and of course works well with the other classes from that API.
Links
- Oracle tutorial: Date Time explaining how to use
java.time. - Documentation: the
Durationclass - Wikipedia article: ISO 8601; section on durations