如何將 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.