Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LocalDateTime in seconds

Tags:

java

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?

like image 329
Joe Avatar asked Dec 04 '25 08:12

Joe


1 Answers

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();
like image 129
assylias Avatar answered Dec 06 '25 20:12

assylias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!