
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert HH:MM:SS Format to Seconds in JavaScript
We are required to write a function that takes in a ‘HH:MM:SS’ string and returns the number of seconds. For example −
countSeconds(‘12:00:00’) //43200 countSeconds(‘00:30:10’) //1810
Let’s write the code for this. We will split the string, convert the array of strings into an array of numbers and return the appropriate number of seconds.
The full code for this will be −
Example
const timeString = '23:54:43'; const other = '12:30:00'; const withoutSeconds = '10:30'; const countSeconds = (str) => { const [hh = '0', mm = '0', ss = '0'] = (str || '0:0:0').split(':'); const hour = parseInt(hh, 10) || 0; const minute = parseInt(mm, 10) || 0; const second = parseInt(ss, 10) || 0; return (hour*3600) + (minute*60) + (second); }; console.log(countSeconds(timeString)); console.log(countSeconds(other)); console.log(countSeconds(withoutSeconds));
Output
The output in the console will be −
86083 45000 37800
Advertisements