In Java 8, an amount of time is represented by the class java.time.Duration
.
I'm not sure if Apache POI has methods to deal directly with a Duration
, so I believe that the best approach is to get the value as String
,
then parse this String
to get the values and add those values to the Duration
:
String s = "46:23:12";
String[] values = s.split(":");
// get the hours, minutes and seconds value and add it to the duration
Duration duration = Duration.ofHours(Integer.parseInt(values[0]));
duration = duration.plusMinutes(Integer.parseInt(values[1]));
duration = duration.plusSeconds(Integer.parseInt(values[2]));
The duration
object will contain the amount equivalent to the input (in this case: 46 hours, 23 minutes and 12 seconds). If you call duration.toString()
, it returns this duration in ISO 8601 format:
PT46H23M12S
Of course this code assumes that the input String
always contains the three fields (hours, minutes and seconds). But you could check for values.length
before parsing the values (and also call the plus
methods only if the respective value is not zero).
If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).
The only difference is the package names (in Java 8 is java.time
and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp
), but the classes and methods names are the same.