如何将 JavaScript 秒转换为分钟和秒?


在本教程中,我们将学习如何将 JavaScript 秒转换为分钟和秒。问题是我们给出了总秒数,我们需要将其表示为分钟和秒的格式。

我们可以执行一些基本的数学运算来解决我们的问题。在这里,我们有两种不同的方法可以将秒转换为分钟和秒。

使用 Math.floor() 方法

在这种方法中,我们将使用Math.floor() 方法。我们将总秒数除以 60 以将其转换为分钟,并应用Math.floor() 方法向下取整浮点数分钟。之后,我们将秒数对 60 取模以获取剩余的秒数。

语法

用户可以按照以下语法将秒转换为分钟和秒。

let minutes = Math.floor(seconds / 60);
let extraSeconds = seconds % 60;
minutes = minutes < 10 ? "0" + minutes : minutes;
extraSeconds = extraSeconds < 10 ? "0" + extraSeconds : extraSeconds;

算法

  • 步骤 1 - 将总秒数除以 60 以将其转换为分钟。

  • 步骤 2 - 对分钟应用 Math.floor() 方法以向下取整。

  • 步骤 3 - 将总秒数对 60 取模以获取剩余的秒数。

  • 步骤 4 - 如果分钟或秒数小于 10,则在它们前面追加 0。

示例

在下面的示例中,我们创建了convertStoMs() 函数,以使用上述算法将秒转换为分钟和秒的格式。我们已经为不同的秒数调用了该函数,用户可以在输出中观察结果。

<html> <head> </head> <body> <h2>Convert seconds to minutes and seconds in JavaScript.</h2> <h4>Using the <i>Math.floor()</i> method to convert the different values of seconds to minutes and seconds.</h4> <p id = "output"></p> <script> let output = document.getElementById("output"); function convertStoMs(seconds) { let minutes = Math.floor(seconds / 60); let extraSeconds = seconds % 60; minutes = minutes < 10 ? "0" + minutes : minutes; extraSeconds = extraSeconds< 10 ? "0" + extraSeconds : extraSeconds; output.innerHTML += seconds + " == " + minutes + " : " + extraSeconds + "<br/>"; } convertStoMs(159); convertStoMs(234567); convertStoMs(9); </script> </body> </html>

使用按位双非 (~~) 运算符

在这种方法中,我们将使用双非 (~~) 运算符向下取整分钟,而不是Math.floor() 方法。双非运算符是 Math.floor() 方法的替代品。

用户可以按照以下语法使用双非运算符。

语法

let minutes = ~~(seconds / 60);
let extraSeconds = seconds % 60;

示例

在下面的示例中,我们将通过将秒数除以 60 并使用双非 (~~) 运算符向下取整来将秒数转换为分钟。为了获得剩余的秒数,我们将对总秒数执行模 60 运算。

<html> <head> </head> <body> <h2>Convert seconds to minutes and seconds in JavaScript.</h2> <h4>Using the <i>Double Not (~~)</i> method to convert the different values of seconds to minutes and seconds.</h4> <p id = "output"></p> <script> let output = document.getElementById("output"); function convertStoMs(seconds) { let minutes = ~~(seconds / 60); let extraSeconds = seconds % 60; output.innerHTML += seconds + " == " + minutes + " : " + extraSeconds + "<br/>"; } convertStoMs(421); convertStoMs(2876); convertStoMs(10); </script> </body> </html>

我们已经学习了两种将总秒数转换为分钟和秒的方法。用户可以使用按位双非 (~~) 运算符使代码更快,因为 Math.floor() 方法比按位运算符慢得多。

更新于: 2022年8月17日

14K+ 浏览量

启动你的职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.