😉

JavaScriptとクッキーでユーザーのタイムゾーンを検出・記憶するスマートWeb時計の作り方

に公開

📝 はじめに

このチュートリアルでは、HTML、CSS、JavaScriptを使用して、ユーザーのローカルタイムゾーンを自動的に検出し、ブラウザのクッキーに保存するスマートな時計を作成します。これは、ユーザーの地域に応じたパーソナライズされたツールやダッシュボードを作成する際に非常に役立ちます。

このガイドの終わりには、以下の機能を備えた完全なWeb時計を作成できます:

  • Intl.DateTimeFormat()を使用してユーザーのタイムゾーンを検出
  • タイムゾーンをクッキーに保存
  • リアルタイムの時刻を表示し、毎秒更新
  • 次回訪問時にタイムゾーンを記憶

この手法は、計算機、ダッシュボード、位置情報に対応したWebアプリなどにも応用可能です。


🧰 使用技術

  • HTML5
  • CSS3
  • JavaScript(バニラ)
  • ブラウザクッキー

🔧 ステップバイステップガイド

  1. HTML構造の作成
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>スマートWeb時計</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="clock-container">
    <h1>あなたのローカル時刻</h1>
    <div id="clock">読み込み中...</div>
    <p id="timezone"></p>
  </div>
  <script src="script.js"></script>
</body>
</html>

  1. CSSでのスタイリング
/* style.css */
body {
  font-family: Arial, sans-serif;
  background-color: #f0f0f0;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0;
}

.clock-container {
  background: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
  text-align: center;
}

#clock {
  font-size: 3rem;
  color: #333;
  margin-top: 10px;
}

#timezone {
  margin-top: 15px;
  font-style: italic;
  color: #555;
}

  1. JavaScriptによる機能追加
// script.js
function getTimeZoneFromCookie() {
  const match = document.cookie.match(/timezone=([^;]+)/);
  return match ? match[1] : null;
}

function setTimeZoneCookie(timeZone) {
  document.cookie = `timezone=${timeZone}; path=/; max-age=31536000`; // 1年間
}

function getCurrentTimeString(timeZone) {
  return new Date().toLocaleTimeString('ja-JP', {
    timeZone: timeZone,
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
}

function updateClock(timeZone) {
  document.getElementById('clock').textContent = getCurrentTimeString(timeZone);
}

window.onload = function () {
  let timeZone = getTimeZoneFromCookie();
  if (!timeZone) {
    timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
    setTimeZoneCookie(timeZone);
  }

  document.getElementById('timezone').textContent = `タイムゾーン: ${timeZone}`;
  updateClock(timeZone);
  setInterval(() => updateClock(timeZone), 1000);
};

✅ まとめ

このスマートWeb時計のプロジェクトは、JavaScriptとブラウザクッキーを活用して、ユーザーに優しいパーソナライズされたWeb体験を提供する良い例です。このアイデアは、計算機、ファイナンスアプリ、スケジューリングダッシュボード、あるいは静的なブログ要素にも簡単に応用可能です。


❓ よくある質問(FAQ)

Q1: クッキーの代わりにlocalStorageを使えますか?

はい、可能です。ただし、クッキーはサーバーからもアクセス可能で、サブドメイン間でも共有できる利点があります。localStorageはブラウザ内だけで動作します。

Q2: 夏時間にも対応していますか?

はい、Intl.DateTimeFormatはシステムとブラウザの最新タイムゾーン情報を使用するため、自動的に夏時間を考慮します。

Q3: すべてのデバイスで正確に動作しますか?

ユーザーのデバイスの内部時計とブラウザの設定に依存します。株式市場のような正確な同期が必要な場合は、NTPサーバーの使用が必要です。

Q4: 複数のタイムゾーンを表示できますか?

もちろん可能です! toLocaleTimeString()に異なるtimeZone値を指定することで、東京、ニューヨークなど複数の時計を表示できます。

Discussion