Timo
Timo

Reputation: 2242

TimeUnit.MILLISECONDS.toSeconds() alternative?

I'm looking to convert an arbitrary value from milliseconds to seconds and my first choice was TimeUnit.MILLISECONDS.toSeconds. However it returns a long and so converts 1 millisecond to 0 seconds instead of 0.001 seconds.

When reading the documentation I can sort of extract that the TimeUnit is specifically meant to go "the other way". Even though I do not understand why they chose this strategy, I'm looking for an (lazy!) alternative that can do this type of conversions.

Upvotes: 1

Views: 2711

Answers (1)

Leo
Leo

Reputation: 6570

well, I think they've tried to cover the "worst case". For example, if you try to convert 1 day into nanos, the number will be larger than the max integer

System.out.println(TimeUnit.DAYS.toNanos(1)); //86400000000000
System.out.println(Integer.MAX_VALUE);        //21474836477

But I agree somehow that numbers can get even bigger than the max long integer in extreme situations. At least the javadoc warns the user about that.

Upvotes: 3

Related Questions