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


要使用JavaScript将HH:MM:SS转换为秒,我们将使用简单的算术运算,例如乘法和加法。我们将通过两个示例代码及其逐步说明来理解这种转换。

在本文中,我们得到一个HH:MM:SS格式的时间,我们的任务是使用JavaScript将HH:MM:SS转换为秒。

将HH:MM:SS转换为秒的步骤

  • 我们使用了两个div来显示时间和以秒为单位的结果。
  • time变量以HH:MM:SS格式存储时间。然后,我们使用split()函数通过冒号分割小时、分钟和秒,并将它们存储在realTime中。
  • 然后,我们使用索引访问存储在realTime中的小时、分钟和秒。我们将小时乘以60*60,将分钟乘以60以转换为秒。
  • 最后,我们使用getElementById()方法和innerHTML访问id为result的div来显示结果。

示例1

这是一个完整的示例代码,实现了上述将HH:MM:SS转换为秒的步骤。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Converting Time to Seconds</title>
</head>
<body>
    <h2>
        Converting HH:MM:SS to seconds with JavaScript
    </h2>
    <div id="time"></div>
    <div id="result"></div>
    <script>
        let time = '10:8:20';
        let realTime = time.split(':');
        let totalSeconds = (+realTime[0]) * 60 * 60 + 
                           (+realTime[1]) * 60 + (+realTime[2]);
        document.getElementById("time")
            .innerHTML= "The time=" + time;
        document.getElementById("result")
            .innerHTML= "Total Seconds=" + totalSeconds;
    </script>
</body>
</html>

示例2

在这个例子中,我们以HH:MM:SS格式从用户那里获取时间作为输入。我们使用了文本type input字段和value属性来获取用户输入的时间,以及一个button,它触发将时间转换为秒的toSec()函数。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Converting Time to Seconds</title>
</head>
<body>
    <h2>
        Converting HH:MM:SS to seconds with JavaScript
    </h2>
    <p>
        In this example, we are accepting time as user input
        to convert time to seconds. 
    </p>
    <label for="timeValue">
        <strong>Enter time (HH:MM:SS):</strong>
    </label>
    <br>
    <input type="text" id="timeValue" placeholder="e.g., 11:13:25">
    <button onclick="toSec()">Convert</button>
    <div id="time"></div>
    <div id="result"></div>
    <script>
        function toSec() {
            let time = document.getElementById('timeValue').value;
            let realTime = time.split(':');
            let totalSeconds = (+realTime[0]) * 60 * 60 + 
                               (+realTime[1]) * 60 + (+realTime[2]);
            document.getElementById("time")
                .innerHTML = "The time = " + time;
            document.getElementById("result")
                .innerHTML = "Total Seconds = " + totalSeconds;
        }
    </script>
</body>
</html>

结论

在本文中,我们了解了如何将HH:MM:SS转换为秒。我们提供了两个将时间转换为秒的示例,在第一个示例中给出了固定时间,在第二个示例中,时间可以由用户输入。

更新于:2024年11月13日

904 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.