如何在 node.js 中设置默认时区?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8083410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I set the default timezone in node.js?
提问by Olu
How do I set the default timezone in node.js?
如何在 node.js 中设置默认时区?
回答by webjprgm
According to this google group thread, you can set the TZ environment variable before calling any date functions. Just tested it and it works.
根据这个 google group thread,您可以在调用任何日期函数之前设置 TZ 环境变量。刚刚测试了它,它的工作原理。
> process.env.TZ = 'Europe/Amsterdam'
'Europe/Amsterdam'
> d = new Date()
Sat, 24 Mar 2012 05:50:39 GMT
> d.toLocaleTimeString()
'06:50:39'
> ""+d
'Sat Mar 24 2012 06:50:39 GMT+0100 (CET)'
You can't change the timezone later though, since by then Node has already read the environment variable.
不过,您以后不能更改时区,因为那时 Node 已经读取了环境变量。
回答by uhef
Another approach which seemed to work for me at least in Linux environment is to run your Node.js application like this:
至少在 Linux 环境中似乎对我有用的另一种方法是像这样运行你的 Node.js 应用程序:
env TZ='Europe/Amsterdam' node server.js
This should at least ensure that the timezone is correctly set already from the beginning.
这至少应该确保从一开始就正确设置了时区。
回答by Vikas Kandari
Here is a 100% working example for getting custom timezone Date Time in NodeJs without using any external modules:
这是一个 100% 工作示例,用于在不使用任何外部模块的情况下在 NodeJs 中获取自定义时区日期时间:
const nDate = new Date().toLocaleString('en-US', {
timeZone: 'Asia/Calcutta'
});
console.log(nDate);
回答by Laurent Couvidou
Unfortunately, setting process.env.TZdoesn't work really well- basically it's indeterminate when the change will be effective).
不幸的是,设置process.env.TZ并不能很好地工作- 基本上不确定更改何时生效)。
So setting the system's timezone before starting node is your only proper option.
因此,在启动节点之前设置系统的时区是您唯一正确的选择。
However, if you can't do that, it should be possible to use node-timeas a workaround: get your times in local or UTC time, and convert them to the desired timezone. See How to use timezone offset in Nodejs?for details.
但是,如果您不能这样做,则应该可以使用节点时间作为解决方法:以本地或 UTC 时间获取您的时间,并将它们转换为所需的时区。请参阅如何在 Nodejs 中使用时区偏移?详情。
回答by Mariano Ruiz
The solution env TZ='Europe/Amsterdam' node server.jsfrom @uhef works in cases where your app doesn't work with forked process, but when you are working with forked process, specially when you launch your app with a building tool like gulp, the command gulpwill take the env values, but the process created by gulpnot (your app).
env TZ='Europe/Amsterdam' node server.js@uhef的解决方案适用于您的应用程序不适用于分叉进程的情况,但是当您使用分叉进程时,特别是当您使用gulp之类的构建工具启动应用程序时,该命令gulp将采用 env 值,但是由gulp创建的进程不是(您的应用程序)。
To solve this, you have to do:
要解决此问题,您必须执行以下操作:
$ export TZ="Europe/Amsterdam"; gulp myTask
This will set the TZenvironment variable for all the process started in the console you are working on, included all the subsequents process executed after the gulp command in the same console without the need to execute them with the prefix export TZ="Europe/Amsterdam";again.
这将为TZ您正在处理的控制台中启动的所有进程设置环境变量,包括在同一控制台中 gulp 命令之后执行的所有后续进程,而无需export TZ="Europe/Amsterdam";再次使用前缀执行它们。
回答by Prajyot Khandeparkar
Set server timezone and use NTP sync. Here is one better solution to change server time.
设置服务器时区并使用 NTP 同步。这是更改服务器时间的一种更好的解决方案。
To list timezones
列出时区
timedatectl list-timezones
To set timezone
设置时区
sudo timedatectl set-timezone America/New_York
Verify time zone
验证时区
timedatectl
I prefer using UTC timezone for my servers and databases. Any conversions must be handled on client. We can make used of moment.js on client side.
我更喜欢为我的服务器和数据库使用 UTC 时区。任何转换都必须在客户端处理。我们可以在客户端使用 moment.js。
It will be easy to maintain many instances as well,
维护许多实例也很容易,
回答by ElBarto
I know this thread is very old, but i think this would help anyone that landed here from google like me.
我知道这个帖子很旧,但我认为这会帮助像我这样从谷歌登陆这里的人。
In GAE Flex (NodeJs), you could set the enviroment variable TZ (the one that manages all date timezones in the app) in the app.yaml file, i leave you here an example:
在 GAE Flex (NodeJs) 中,你可以在 app.yaml 文件中设置环境变量 TZ(管理应用程序中所有日期时区的变量),我在这里给你一个例子:
app.yaml
应用程序.yaml
# [START env]
env_variables:
# Timezone
TZ: America/Argentina/Buenos_Aires
回答by pscl
Here's an answer for those deploying a Node.js application to Amazon AWS Elastic Beanstalk. I haven't seen this documented anywhere else:
这是将 Node.js 应用程序部署到 Amazon AWS Elastic Beanstalk的答案。我在其他任何地方都没有看到这个记录:
Under Configuration -> Software -> Environment Properties, simply set the key value pair TZand your time zone e.g. America/Los Angeles, and Apply the change.
在 下Configuration -> Software -> Environment Properties,只需设置键值对TZ和您的时区,例如America/Los Angeles,然后应用更改。
You can verify the effect by outputting new Date().toString()in your Node app and paying attention to the time zone suffix.
您可以通过new Date().toString()在您的 Node 应用程序中输出并注意时区后缀来验证效果。
回答by Nick
As of Node 13, you can now repeatedly set process.env.TZand it will be reflected in the timezone of new Date objects. I don't know if I'd use this in production code but it would definitely be useful in unit tests.
从 Node 13 开始,您现在可以重复设置process.env.TZ,它将反映在新 Date 对象的时区中。我不知道我是否会在生产代码中使用它,但它在单元测试中肯定有用。
> process.env.TZ = 'Europe/London';
'Europe/London'
> (new Date().toString())
'Fri Mar 20 2020 09:39:59 GMT+0000 (Greenwich Mean Time)'
> process.env.TZ = 'Europe/Amsterdam';
'Europe/Amsterdam'
> (new Date().toString())
'Fri Mar 20 2020 10:40:07 GMT+0100 (Central European Standard Time)'
回答by BillyBob - Fire Fight'n PrgrmR
Sometimes you may be running code on a virtual server elsewhere - That can get muddy when running NODEJS or other flavors.
有时您可能会在其他地方的虚拟服务器上运行代码 - 在运行 NODEJS 或其他风格时可能会变得混乱。
Here is a fix that will allow you to use any timezone easily.
这是一个修复程序,可让您轻松使用任何时区。
Check here for list of timezones
Just put your time zone phrase within the brackets of your FORMAT line.
只需将您的时区短语放在 FORMAT 行的括号内。
In this case - I am converting EPOCH to Eastern.
在这种情况下 - 我将 EPOCH 转换为 Eastern。
//RE: https://www.npmjs.com/package/date-and-time
const date = require('date-and-time');
let unixEpochTime = (seconds * 1000);
const dd=new Date(unixEpochTime);
let myFormattedDateTime = date.format(dd, 'YYYY/MM/DD HH:mm:ss A [America/New_York]Z');
let myFormattedDateTime24 = date.format(dd, 'YYYY/MM/DD HH:mm:ss [America/New_York]Z');

