如何修改脚本使其基于指定时区(如Europe/London)执行?
Got it, let's sort out this timezone mismatch issue! Since your server defaults to America/Detroit, any date operations will use that timezone unless you explicitly tell them otherwise. Here's how to adjust your code to get the Europe/London time you need:
Option 1: Explicitly Set Timezone in toLocaleString
The simplest and safest approach is to pass a timezone option directly to the toLocaleString method. This only affects this specific date conversion, so you won't break other parts of your script that rely on the server's default timezone.
Replace your existing line with this code:
// Parse the raw timestamp from your data const updatedDate = new Date(res.data.statuses[1]['services_platforms'][0].updated); // Convert to Europe/London timezone with your desired format const londonTime = updatedDate.toLocaleString('en-GB', { timeZone: 'Europe/London', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }); // Adjust to match the "YYYY-MM-DDTHH:mm:ss" format from your example const formattedLondonTime = londonTime.replace(', ', 'T'); console.log(formattedLondonTime); // Outputs something like "2020-10-01T04:09:50" (adjusted for London's timezone)
Quick Breakdown:
'en-GB'ensures the date uses UK-style formatting (we’ve forced 2-digit month/day to align with your desired output)timeZone: 'Europe/London'tells the method to use London’s timezone, including automatic daylight saving adjustments- The date/time options (
year,month, etc.) enforce the exact parts you need - The final
replaceswaps the comma-space separator for aTto match your original output structure
Option 2: Set Global Timezone (Not Recommended for Most Cases)
If every date operation in your script needs to use Europe/London timezone, you can set the TZ environment variable when running your Node.js script:
TZ='Europe/London' node your-script.js
This makes all Date operations default to London’s timezone. However, be careful with this—it might break other parts of your app that expect the server’s default Detroit timezone.
Important Note:
All modern Node.js versions and browsers support the timeZone option in toLocaleString, but if you’re stuck on an extremely old runtime, you might need a fallback like date-fns-tz or moment-timezone.
内容的提问来源于stack exchange,提问作者Johnty

