將毫秒轉換成 hh:mm:ss (有解說轉換時分秒的原理)

You had a timestamp in seconds that you wanted to display in HH:MM:SS format.

var timestamp = 9462; // milliseconds

轉換小時

There are 60 seconds in a minute, and 60 minutes in an hour. We’ll divide our timestamp by 60, and then by 60 again. That leaves us with 2.6283 repeating. We want just hours, though. We can use Math.floor() to round down to the nearest whole number.

var timestamp = 9462;

// 2
var hours = Math.floor(timestamp / 60 / 60);

轉換分鐘

There are 60 seconds in a minute. Let’s divide our timestamp by 60, and use Math.floor() to round down to the nearest whole number. That leaves us with 157.

// 157
var minutes = Math.floor(timestamp / 60);

We’ll multiply our hours by 60 to get its value in minutes, then subtract to it from our minutes to get the correct value. (minutes 裡包含 hours,要把 hours 換算成 minutes 後扣除)

var timestamp = 9462;

// 2
var hours = Math.floor(timestamp / 60 / 60);

// 37
var minutes = Math.floor(timestamp / 60) - (hours * 60);

轉換秒數

We can use the remainder operator. It returns the amount leftover after dividing by a number.

We’ll use it to divide our timestamp by 60 (the number of seconds in a minute). The number we get back is the seconds after we remove all of the minutes.

var timestamp = 9462;

// 2
var hours = Math.floor(timestamp / 60 / 60);

// 37
var minutes = Math.floor(timestamp / 60) - (hours * 60);

// 42
var seconds = timestamp % 60;

格式化時間呈現 HH:MM:SS

Now that we have our hours, minutes, and seconds, we’re ready to format them into our HH:MM:SS format.

We can use toString() to convert our numbers to strings and use the padStart() method to enforce a minimum number of digits.

// 02:37:42
var formatted = hours.toString().padStart(2, '0') + ':' + minutes.toString().padStart(2, '0') + ':' + seconds.toString().padStart(2, '0');

補充

:see_no_evil: String.padStart()
Add characters to the beginning of a string if it’s less than a certain length. Accepts two arguments: the length the string should be, and what characters to add if it’s not that length.

// Add a leading zero for hours below 10
var hour3 = '3';
var hour12 = '12';

// returns "03"
hour3.padStart(2, '0');

// returns "12"
hour12.padStart(2, '0');

相關閱讀

How to convert seconds to minutes and hours with vanilla JS

1個讚