0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JavaScript】分を時間に変換する方法

Posted at

基本的な変換方法

分を時間単位に変換するには、Math.floor()と剰余演算子%を使用します。

let m = 66;
console.log(`${Math.floor(m / 60)}時間${m % 60}分`);
// 出力: 1時間6分

m = 300;
console.log(`${Math.floor(m / 60)}時間${m % 60}分`);
// 出力: 5時間0分

m = 59;
console.log(`${Math.floor(m / 60)}時間${m % 60}分`);
// 出力: 0時間59分

h:mm形式への変換

時刻表示のような「h:mm」形式にする場合は、1桁の分を0埋めします。

const minutesToTime = (minutes) => {
  const hours = Math.floor(minutes / 60);
  const mins = minutes % 60;
  return `${hours}:${mins >= 10 ? mins : '0' + mins}`;
};

console.log(minutesToTime(66));   // 1:06
console.log(minutesToTime(300));  // 5:00
console.log(minutesToTime(125));  // 2:05

入力フォームから分を受け取り、時間形式で表示する例です。

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>分を時間に変換</title>
</head>
<body>
  <input id="minutes" type="number" placeholder="分を入力">
  <button id="convertBtn">変換</button>
  <p id="result"></p>

  <script>
    const convertBtn = document.getElementById('convertBtn');
    const minutes = document.getElementById('minutes');
    const result = document.getElementById('result');

    convertBtn.onclick = () => {
      const m = parseInt(minutes.value);
      const hours = Math.floor(m / 60);
      const mins = m % 60;
      result.textContent = `${hours}:${mins >= 10 ? mins : '0' + mins}`;
    };
  </script>
</body>
</html>
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?