如何实现JavaScript日期本地时间与UTC互转?附现有moment函数问题
Hey there, let's break down your time conversion code. It looks like you're trying to toggle between displaying a date as UTC and local time, but there's a critical flaw in the current logic that's likely causing incorrect results after the first switch.
The Issue with Your Current Code
When you start out, currentTimeZone is set to utc, so using moment.utc(input, fmt) to parse the initial UTC string works perfectly. You convert it to local time, update input, and switch the timezone flag to local.
Here's where things go wrong: when you click the button again, you still use moment.utc(input, fmt) to parse the string—but that string is now a local time, not UTC. Moment.js will interpret your local time as UTC, which completely throws off the conversion.
The Corrected Code
We need to adjust how we parse the input string based on the current timezone state. Here's the fixed version:
var input = "December 25, 2018 01:02:20"; var fmt = 'MMMM DD, YYYY HH:mm:ss'; var currentTimeZone = "utc"; // Initial state: input is UTC time function convertUtcToLocalViceVersa() { console.log(`Current input: ${input}`); let momentObj; if (currentTimeZone === 'utc') { // Parse the UTC string, convert to local time momentObj = moment.utc(input, fmt); input = momentObj.local().format(fmt); currentTimeZone = "local"; } else { // Parse the local time string, convert to UTC momentObj = moment(input, fmt); // Equivalent to moment.local(input, fmt) input = momentObj.utc().format(fmt); currentTimeZone = "utc"; } console.log(`Converted result: ${input} (Current mode: ${currentTimeZone})`); }
Key Fixes Explained
- Conditional parsing: We now use
moment.utc()only when we confirm the input is a UTC string. When the input is local time, we use standardmoment()(which defaults to local timezone parsing) to correctly interpret the string. - Transparent logging: Added console logs to track the input, output, and current mode—this makes it easy to debug if you run into edge cases.
- Consistent state tracking: The
currentTimeZoneflag always matches what theinputstring represents, so we never misinterpret the time's timezone origin.
How It Works in Practice
- Start with UTC time:
December 25, 2018 01:02:20 - First button click: Converts to your local time (e.g.,
December 25, 2018 09:02:20for UTC+8) and switches mode tolocal - Second button click: Converts that local time back to the original UTC string and switches mode to
utc - This cycle repeats correctly every time you click the button.
内容的提问来源于stack exchange,提问作者Rolando

