I have a String in the format of hh:mm:ss. It is a duration of a telephone call.
I want to get the duration of that call in seconds.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss");
LocalDateTime time = LocalDateTime.parse(timeStr, formatter);
How can I get the duration in seconds from the LocalDateTime?
There is no date component, so you can simply use a LocalTime, although LocalTime is not really designed to represent a duration:
String input = "01:52:27";
LocalTime time = LocalTime.parse(input);
int seconds = time.toSecondOfDay();
Note that this will only work for durations up to 23:59:59.
A better approach would be to use the Duration class - note that it will also cope with longer durations:
//convert first to a valid Duration representation
String durationStr = input.replaceAll("(\\d+):(\\d+):(\\d+)", "PT$1H$2M$3S");
Duration duration = Duration.parse(durationStr);
int seconds = duration.getSeconds();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With