如何將 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() 方法比按位運算子慢得多。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP