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
}
java.timeclasses can be used, you should. SDF is (in Java) supersededSimpleDateFormat, neither here nor anywhere at all. It was a notorious troublemaker of a class and for that reason replaced by java.time and itDateTimeFormatterclass about a decade ago. However neitherSimpleDateFormatnorDateTimeFormatterare 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.Duration.parse("01:00:23.000".replaceFirst("^(\\d{2}):(\\d{2}):(\\d{2}\\.\\d{3})$", "PT$1H$2M$3S")). Yields aDurationof 1 hour 23 seconds. Keep theDurationobject if you can, or use itstoSecondsmethod to convert to along. I first convert your string to ISO 8601 format,PT01H00M23.000S, because this is whatDuration.parse()accepts. Then that class takes care of the rest.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.