javascript タイムゾーンを取得する

javascript タイムゾーンを取得する

javascriptで、タイムゾーンを取得するサンプルコードを掲載してます。「Intl.DateTimeFormat()」を使用して取得します。1行のコードで取得できます。ブラウザはchromeを使用しています。

環境

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

タイムゾーンを取得

タイムゾーンを取得するには、「Intl.DateTimeFormat()」を使用します。

let tz = Intl.DateTimeFormat().resolvedOptions().timeZone;

console.log(tz);

実行結果

サンプルコード

以下は、
「実行」ボタンをクリックした際に、タイムゾーンを取得して表示するサンプルコードとなります。

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

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

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
</head>

<script>

  window.onload = () => {

    btn.onclick = () => { foo.innerHTML = Intl.DateTimeFormat().resolvedOptions().timeZone };

  }

</script>

<body>
  <div class="container mx-auto my-56 w-64 px-4">

    <div id="sample" class="flex flex-col justify-center">

      <h1 class="font-semibold text-pink-500 text-lg mr-auto">実行結果</h1>

      <p id="foo" class="font-semibold text-lg mr-auto"></p>

      <button id="btn"
        class="mb-2 md:mb-0 bg-transparent hover:bg-blue-500 text-blue-700 font-semibold hover:text-white py-2 px-4 border border-blue-500 hover:border-transparent rounded">
        実行
      </button>

    </div>

  </div>
</body>

</html>

実行結果を確認すると、タイムゾーンが表示されていることが確認できます。