0

I am using simple date format to convert the following into number of seconds

Input : 00:00:10.000 , 00:05:10.000, 01:00:23.000

Expected output : 10 seconds , 310 seconds , 3623 seconds

Below is how I am trying but it gives negative value

fun String.convertTimeIntoSeconds(): Long {
val dateFormat: DateFormat = SimpleDateFormat("HH:mm:ss.SSS")
val date = dateFormat.parse(this)
val seconds = date.time / 1000L
return seconds
}
4
  • 4
    Not Java, but if the java.time classes can be used, you should. SDF is (in Java) superseded Commented Apr 26, 2023 at 10:33
  • 1
    I strongly recommend that you do not use SimpleDateFormat, neither here nor anywhere at all. It was a notorious troublemaker of a class and for that reason replaced by java.time and it DateTimeFormatter class about a decade ago. However neither SimpleDateFormat nor DateTimeFormatter are for parsing an amount of time. They are only for parsing (and formatting) a date and/or time of day. You need to search for how to parse a duration using java.time. There are some questions and some good answers out there. Commented Apr 26, 2023 at 12:23
  • It’s not very readable, but works for parsing (Java syntax): Duration.parse("01:00:23.000".replaceFirst("^(\\d{2}):(\\d{2}):(\\d{2}\\.\\d{3})$", "PT$1H$2M$3S")). Yields a Duration of 1 hour 23 seconds. Keep the Duration object if you can, or use its toSeconds method to convert to a long. I first convert your string to ISO 8601 format, PT01H00M23.000S, because this is what Duration.parse() accepts. Then that class takes care of the rest. Commented Apr 26, 2023 at 12:29
  • (A) Duration.between ( LocalTime.MIN , LocalTime.parse ( "00:05:10.000" ) ).toSeconds() per my Answer on original Question. See code run. (B) Educate the publisher of your data about using standard ISO 8601 formats for a duration rather than ambiguous clock-time formats. Ex: PT5M10S. See Comment by Ole V.V. Commented Apr 27, 2023 at 18:56

2 Answers 2

0
fun String.convertTimeIntoSeconds(): Long {
    val dateFormat: DateFormat = SimpleDateFormat("HH:mm:ss.SSS")
    dateFormat.timeZone = TimeZone.getTimeZone("UTC") // set time zone to UTC
    val date = dateFormat.parse(this)
    val seconds = date.time / 1000L
    return seconds
}

This should work (:

Sign up to request clarification or add additional context in comments.

Comments

0

(Since posted in Java) I'd do something like:

public static String timeDigitsToSecs(String s) {
    //("HH:mm:ss.SSS" format)
    String[] atoms = s.split("[:.]");
    Duration d = Duration.ofHours(Long.parseLong(atoms[0]))
        .plusMinutes(Long.parseLong(atoms[1]))
        .plusSeconds(Long.parseLong(atoms[2]))
        .plusMillis(Long.parseLong(atoms[3]));
    return String.valueOf(d.toSeconds());
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.