Suppose time is given in MM:SS(ex- 02:30) OR HH:MM:SS in String format.how can we convert this time to second.
const d = '02:04:33'; // your input string const a = hms. split(':'); // split it at the colons const result = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]); console. log(result); Try Lightrun to collect production stack traces without stopping your Java applications!
Solution 1. Split the string into its component parts. Get the number of minutes from the conversion table. Multiply that by the number and that is the number of minutes.
Example 2: Convert Milliseconds to Minutes and Seconds fun main(args: Array<String>) { val milliseconds: Long = 1000000 val minutes = milliseconds / 1000 / 60 val seconds = milliseconds / 1000 % 60 println("$milliseconds Milliseconds = $minutes minutes and $seconds seconds.") }
In your case, using your example you could use something like the following:
String time = "02:30"; //mm:ss
String[] units = time.split(":"); //will break the string up into an array
int minutes = Integer.parseInt(units[0]); //first element
int seconds = Integer.parseInt(units[1]); //second element
int duration = 60 * minutes + seconds; //add up our values
If you want to include hours just modify the code above and multiply hours by 3600 which is the number of seconds in an hour.
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