如何用JavaScript及analogClockJs实现多时区时钟与跨时区同时间显示?
Alright, let's break down how to solve both of your requirements clearly—first handling consistent time display across different timezones in JavaScript, then building multi-timezone analog clocks with analogClockJs. Here's a step-by-step guide with working code:
When you need users in different timezones to see the exact same time, you can't rely on local time (since it shifts based on the user's system settings). Instead, work with UTC (Coordinated Universal Time) or explicitly target a specific timezone.
Option 1: Display UTC Time Directly
Use JavaScript's built-in UTC methods to pull and format universal time, which stays consistent for all users:
function formatUTCTime() { const now = new Date(); // Get UTC-specific date/time components const year = now.getUTCFullYear(); const month = String(now.getUTCMonth() + 1).padStart(2, '0'); const date = String(now.getUTCDate()).padStart(2, '0'); const hours = String(now.getUTCHours()).padStart(2, '0'); const minutes = String(now.getUTCMinutes()).padStart(2, '0'); const seconds = String(now.getUTCSeconds()).padStart(2, '0'); return `${year}-${month}-${date} ${hours}:${minutes}:${seconds} UTC`; } // Example usage: Logs the same UTC time for every user console.log(formatUTCTime());
Option 2: Display a Specific Timezone's Time
If you want all users to see the time in a single target timezone (e.g., New York), use Intl.DateTimeFormat with the timeZone parameter:
function formatSpecificTimezone(timezone = 'America/New_York') { const now = new Date(); return new Intl.DateTimeFormat('en-US', { timeZone: timezone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }).format(now); } // Example usage: Shows New York time to every user console.log(formatSpecificTimezone());
analogClockJs is a lightweight, customizable library built with vanilla JS and CSS. To render clocks for different timezones, you just need to pass the correct timezone-specific time to each clock instance. Below is a complete, working implementation:
Step 1: Prepare HTML & Base Styles
Create containers for each clock and add basic styling:
<style> /* Basic clock styling */ .clock { width: 220px; height: 220px; border: 3px solid #2d2d2d; border-radius: 50%; margin: 20px; display: inline-block; position: relative; text-align: center; padding-top: 15px; font-family: Arial, sans-serif; } /* Digital time display */ .digital-time { font-size: 14px; margin-bottom: 10px; } /* Clock hands */ .hour-hand, .minute-hand, .second-hand { position: absolute; bottom: 50%; left: 50%; transform-origin: bottom center; background-color: #2d2d2d; } .hour-hand { width: 4px; height: 60px; margin-left: -2px; } .minute-hand { width: 3px; height: 85px; margin-left: -1.5px; } .second-hand { width: 2px; height: 95px; margin-left: -1px; background-color: #e74c3c; } </style> <!-- Clock containers for different timezones --> <div id="ny-clock" class="clock"></div> <div id="london-clock" class="clock"></div> <div id="beijing-clock" class="clock"></div>
Step 2: Complete the analogClockJs Constructor
Here's the full implementation (building on the code snippet you provided) with timezone support:
function AnalogClock(id, options = {}, dateStr) { const container = document.getElementById(id); if (!container) return; // Merge default and user-provided options const config = { showDigital: true, ...options }; // Format date/time for digital display const formatDateTime = (time) => { const year = time.getFullYear(); const month = String(time.getMonth() + 1).padStart(2, '0'); const date = String(time.getDate()).padStart(2, '0'); const hours = String(time.getHours()).padStart(2, '0'); const minutes = String(time.getMinutes()).padStart(2, '0'); const seconds = String(time.getSeconds()).padStart(2, '0'); return `${year}-${month}-${date}<br>${hours}:${minutes}:${seconds}`; }; // Initialize time: use provided timezone time or local time let currentTime = dateStr ? new Date(dateStr) : new Date(); // Build the clock DOM structure const initClock = () => { // Add digital time if enabled if (config.showDigital) { const digitalEl = document.createElement('div'); digitalEl.className = 'digital-time'; digitalEl.innerHTML = formatDateTime(currentTime); container.appendChild(digitalEl); } // Create container for clock hands const handsContainer = document.createElement('div'); handsContainer.style.position = 'absolute'; handsContainer.style.top = '0'; handsContainer.style.left = '0'; handsContainer.style.width = '100%'; handsContainer.style.height = '100%'; container.appendChild(handsContainer); // Create hour, minute, and second hands ['hour', 'minute', 'second'].forEach(handType => { const hand = document.createElement('div'); hand.className = `${handType}-hand`; handsContainer.appendChild(hand); }); }; // Update clock hand angles based on current time const updateHands = () => { const seconds = currentTime.getSeconds(); const minutes = currentTime.getMinutes(); const hours = currentTime.getHours() % 12; // Calculate rotation angles const secondAngle = (seconds / 60) * 360; const minuteAngle = (minutes / 60) * 360 + (seconds / 60) * 6; const hourAngle = (hours / 12) * 360 + (minutes / 60) * 30; // Apply rotations to hands container.querySelector('.second-hand').style.transform = `rotate(${secondAngle}deg)`; container.querySelector('.minute-hand').style.transform = `rotate(${minuteAngle}deg)`; container.querySelector('.hour-hand').style.transform = `rotate(${hourAngle}deg)`; // Update digital time if (config.showDigital) { container.querySelector('.digital-time').innerHTML = formatDateTime(currentTime); } }; // Start the clock initClock(); updateHands(); // Refresh every second setInterval(() => { currentTime.setSeconds(currentTime.getSeconds() + 1); updateHands(); }, 1000); } // Helper function to get current time for a specific timezone const getTimezoneCurrentTime = (timezone) => { // Convert local time to target timezone time return new Date(new Date().toLocaleString('en-US', { timeZone: timezone })).toISOString(); }; // Initialize clocks for different timezones AnalogClock('ny-clock', {}, getTimezoneCurrentTime('America/New_York')); AnalogClock('london-clock', {}, getTimezoneCurrentTime('Europe/London')); AnalogClock('beijing-clock', {}, getTimezoneCurrentTime('Asia/Shanghai'));
Key Notes
- Timezone Handling: The
getTimezoneCurrentTimefunction converts the user's local time to the target timezone usingtoLocaleString, then passes it to the clock constructor. - Customization: Adjust the
configobject or CSS styles to modify clock size, colors, digital display visibility, and more. - Real-Time Updates: The
setIntervalfunction ensures each clock updates every second to stay accurate.
内容的提问来源于stack exchange,提问作者Ghulam Abbas

