javascript 時刻を午前(AM)・午後(PM)形式で表示する

javascript 時刻を午前(AM)・午後(PM)形式で表示する

javascriptで、時刻を午前(AM)・午後(PM)形式で表示するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 104.0.5112.81

午前(AM)・午後(PM)形式で表示

午前(AM)・午後(PM)形式で表示するには、「toLocaleString」を使用する方法があります。

const d = new Date();

console.log(
    d.toLocaleString('ja-JP', { hour: 'numeric', hour12: true })
);  

console.log(
    d.toLocaleString('en-US', { hour: 'numeric', hour12: true })
);

実行結果

以下のように、関数を使用して、任意の位置に「午後や午前」を指定することも可能です。

const f = (date) => {

  let h = date.getHours();

  let m = date.getMinutes();    

  const str = h >= 12 ? '午後' : '午前';

  h %= 12;
  h = h ? h : 12; // 0 のときは12時に変更する

  m = m < 10 ? `0${m}` : m; // 10分未満の場合0を付与

  const t = `${str} ${h}:${m} `;

  return t;

};

console.log( f(new Date()) );

実行結果

サンプルコード

以下は、
「実行」ボタンをクリックすると、現在日時を取得して「AM・PM」を付与して表示する
サンプルコードとなります。

※cssには「tailwind」を使用してます。関数はアロー関数を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
    <meta charset="utf-8" />
    <title>mebeeサンプル</title>
    <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet" />
</head>

<script>

    window.onload = () => {
        // クリックイベントを登録
        btn.onclick = () => {
            result.textContent = f(new Date())
      }; // document.getElementById('btn');を省略
    };

    const f = (date) => {

        let h = date.getHours();

        let m = date.getMinutes();

        const str = h >= 12 ? 'PM' : 'AM';

        h %= 12;
        h = h ? h : 12; // 0 のときは12時に変更する

        m = m < 10 ? `0${m}` : m; // 10分未満の場合0を付与

        const t = `${str} ${h}:${m} `;

        return t;

    };

</script>

<body>
    <div class="container mx-auto my-56 w-56 px-4">
        <div class="flex justify-center">
            <p id="result" class="bg-teal-500 text-white py-2 px-4 rounded-full mb-3 mt-4">
                実行結果
            </p>
        </div>

        <div class="flex justify-center">
            <button id="btn" type="button"
                class="mt-5 bg-transparent border border-red-500 hover:border-red-300 text-red-500 hover:text-red-300 font-bold py-2 px-4 rounded-full">
                実行
            </button>
        </div>
    </div>
</body>

</html>

AMかPM付きで表示されていることが確認できます。