JavaScript获取MT/ET时区时间异常求助:兼容夏令时不受PST影响
Hey there! I get it—that frustrating issue where your script pulls the wrong timezone when you're in PST is definitely solvable. The key mistake here is probably relying on your local system's timezone to calculate MT/ET times instead of explicitly targeting those specific timezones directly. Here's how to fix it, with examples for common scripting languages:
Core Principle
Instead of calculating offsets from your local time (which breaks when you're in a different timezone or during DST shifts), use IANA Timezone Identifiers (like America/Denver for Mountain Time, America/New_York for Eastern Time). These identifiers are tied to official timezone databases that automatically handle daylight saving time transitions, so you don't have to manually track those rules.
Example 1: Python (3.9+)
Use the built-in zoneinfo module (for older Python versions, use pytz instead—same logic applies):
from datetime import datetime from zoneinfo import ZoneInfo # Get current Mountain Time (MT) current_mt = datetime.now(ZoneInfo("America/Denver")) print(f"Current Mountain Time: {current_mt.strftime('%Y-%m-%d %H:%M:%S')}") # Get current Eastern Time (ET) current_et = datetime.now(ZoneInfo("America/New_York")) print(f"Current Eastern Time: {current_et.strftime('%Y-%m-%d %H:%M:%S')}")
This will always return the correct MT/ET time, regardless of where your script is running, and automatically switches between standard and daylight saving time.
Example 2: JavaScript (Node.js/Browser)
For Node.js, use the luxon library (it's lightweight and timezone-aware). For browsers, you can use native Intl.DateTimeFormat or luxon:
// Node.js with luxon const { DateTime } = require('luxon'); // Fetch MT time const mt_now = DateTime.now().setZone('America/Denver'); console.log(`Current Mountain Time: ${mt_now.toFormat('yyyy-MM-dd HH:mm:ss')}`); // Fetch ET time const et_now = DateTime.now().setZone('America/New_York'); console.log(`Current Eastern Time: ${et_now.toFormat('yyyy-MM-dd HH:mm:ss')}`); // Browser-native alternative const mt_formatter = new Intl.DateTimeFormat('en-US', { timeZone: 'America/Denver', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }); console.log('Current Mountain Time:', mt_formatter.format(new Date()));
Key Tips to Avoid Future Issues
- Never use fixed UTC offsets (like UTC-7 for MT): These change during DST (MT becomes UTC-6 in daylight saving time), so hardcoding offsets will break half the year.
- Keep your timezone data updated: Libraries like
pytz,zoneinfo, andluxonregularly update their timezone databases to reflect any changes to DST rules (yes, these do get adjusted occasionally!). - Test across timezones: If possible, run your script in a PST environment (or simulate it) to confirm MT/ET times show up correctly.
内容的提问来源于stack exchange,提问作者jamiechalski

