使用 JavaScript 将 HH:MM:SS 转换为秒

使用 JavaScript 将 HH:MM:SS 转换为秒

Convert HH:MM:SS to Seconds using JavaScript

转换hh:mm:ss为秒:

  1. 通过乘以60两倍将小时数转换为秒数。
  2. 通过乘以将分钟转换为秒60
  3. 将小时和分钟的结果与秒相加以获得最终值。
索引.js
const str = '09:30:16'; const [hours, minutes, seconds] = str.split(':'); function convertToSeconds(hours, minutes, seconds) { return Number(hours) * 60 * 60 + Number(minutes) * 60 + Number(seconds); } console.log(convertToSeconds(hours, minutes, seconds)); // 👉️ 34216
我们创建了一个可重用的函数,它将小时、分钟和秒作为参数并将它们转换为秒。

示例中的字符串格式为hh:mm:ss,但这可以是任何其他格式。

In the example, we split the string on each colon, to get an array of
substrings. The array contains the hours, minutes and seconds.

index.js
const str = '09:30:16'; // 👇️ ['09', '30', '16'] console.log(str.split(':'))

We then directly assigned the values to the hours, minutes and seconds
variables using array destructuring.

To convert the hours to seconds, we had to multiple the value by 60 twice – once to convert to minutes and the second time to convert to seconds.

To convert the minutes to seconds, we multiplied by 60 once.

Because the results of the split operation are strings, we converted each value
to a number and added them to one another.

If you only have a string that contains the hours and minutes (hh:mm), you can
slightly tweak the function to convert to seconds.

index.js
const str = '09:30'; const [hours, minutes] = str.split(':'); function convertToSeconds(hours, minutes) { return Number(hours) * 60 * 60 + Number(minutes) * 60; } console.log(convertToSeconds(hours, minutes)); // 👉️ 34200

上面的字符串格式为hh:mm,所以我们去掉函数的第三个参数,将小时和分钟转换为秒。