Vito Vito - 11 months ago 66
Java Question

How to parse String containing time units (ms/ns/ps/fs etc) to double in Java

How to parse String expressing time (containing double and timeunit suffix (ms/ns/ps/picosecond(s)/us/fs/msec/ miliseconds etc... )) into double second. Is there any standard library that does the trick in a robust way? I believe it should be within some basic physics/engineering libs but yet i did not come across any.

E.g. Input:

"1.23 ms"
"0.98 ns"
"33 s"




Answer Source

Thought about deleting the answer but I feel editing and making it correct with additional information may make more sense.

Yes its correct. JODA API does not support precisions beyond milliseconds. Found another stackoverflow link and perusing it I found that moving to java.time api from Java 8 should be the right decision.

I've just checked their official website which itself suggests moving to Java 8 based java.time (JSR-310) in future.

Here is another link that would help you understand more on the differences in Java 8's based Date/Time api with JODA

If you need calculations based on precisions with milliseconds and are using JDK versions prior to Java 8, then you can try JODA.