You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将NodeJS本地环境时区设置为与生产环境一致(UTC)

Fixing UTC Timezone Alignment in Local Express Server

Got it, let’s sort this out so your local environment matches production’s UTC timezone without changing code—perfect that you want consistency between environments!

1. Use an Environment Variable (No Code Changes Needed)

This is the best approach because it keeps your code identical across local and production, and you don’t have to mess with system settings. Node.js respects the TZ environment variable, so you just need to set it to UTC when starting your Express server.

  • Windows (Command Prompt):
    set TZ=UTC && node app.js
    
  • Windows (PowerShell):
    $env:TZ="UTC"; node app.js
    
  • macOS/Linux (Bash/Zsh):
    TZ=UTC node app.js
    

To make this even easier, add it to your package.json scripts so you can just run npm start like usual:

{
  "scripts": {
    "start": "TZ=UTC node app.js"
  }
}

Now everyone on your team will run the server in UTC automatically, no manual setup required.

2. Optional: Use a Date Library for Rock-Solid Consistency

If you want extra insurance against timezone bugs (even if the server’s timezone is set), use a library like date-fns-tz (modern alternative to Moment.js) to explicitly handle dates in UTC. For example:

const { formatInTimeZone } = require('date-fns-tz');

// Format any date to UTC, regardless of server timezone
const utcTimestamp = formatInTimeZone(new Date(), 'UTC', 'yyyy-MM-dd HH:mm:ss');

This is a good addition if your project does a lot of date parsing/formatting, but it does require small code changes—so only use it if you need that extra layer of safety.

3. Is This a System Setting Issue?

Not exactly. Node.js defaults to your system’s timezone, but you don’t need to change your OS settings to fix this. The TZ environment variable overrides the system timezone just for your Node.js process, which is far more flexible (especially if you work on multiple projects that need different timezones).

By using the TZ=UTC approach, you’ll eliminate that 5-hour EST/UTC difference entirely, keeping your local date behavior identical to production.

内容的提问来源于stack exchange,提问作者Phil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:33:16