默认时区在所有模块之间共享:
服务器.js
var moment = require('moment-timezone');
console.log('sets timezone to Europe/Stockholm and locale to sv');
moment.tz.setDefault('Europe/Stockholm');
moment.locale('sv');
var moduleA = require('./moduleA');
var moduleB = require('./moduleB');
模块A.js
var moment = require('moment-timezone');
setInterval(function () {
console.log('Moment in moduleA', moment().format('MMMM Do YYYY, h:mm:ss a'));
}, 100)
模块B.js
var moment = require('moment-timezone');
setInterval(function () {
console.log('Moment in moduleB', moment().format('MMMM Do YYYY, h:mm:ss a'));
}, 100)
setInterval(function () {
console.log('Changing timezone in moduleB America/New_York locale en');
moment.tz.setDefault("America/New_York");
moment.locale('en');
}, 3000);
3秒后输出:
Moment in moduleA februari 8e 2017, 9:09:19 am
Moment in moduleB februari 8e 2017, 9:09:19 am
Moment in moduleA februari 8e 2017, 9:09:19 am
Moment in moduleB februari 8e 2017, 9:09:19 am
Changing timezone in moduleB America/New_York locale en
Moment in moduleA February 8th 2017, 3:09:19 am
Moment in moduleB February 8th 2017, 3:09:19 am
Moment in moduleA February 8th 2017, 3:09:19 am
这是什么环境?
节点 4.7.3,Ubuntu 14.04
我认为我们应该在文档中添加一个警告,而不是建议开发人员不要在像 node.js 这样的系统中使用这个功能。
http://momentjs.com/timezone/docs/#/using -timezones/default-timezone/
像这样的东西:
https://github.com/mashpie/i18n-node#example -usage-in-global-scope
moment.tz.setDefault() 显然是模块 moment.tz 的全局配置方法
不确定在节点中只需要导入模块 moment.timezone 一次而不是几次是否正确。 如果它是真的,那么示例输出是预期的。
@alburthoffman是的,这是预期的输出,但我认为很多人在节点环境中可能会遇到问题,因为依赖项列表中较靠后的模块可以使用 setDefault 执行某些操作,并且会对所有具有 require('时刻-时区')。 我花了很多时间才做对了。
如果你们同意我们可以添加这样的信息文本: https :
如果我们能有这样的东西,那就太好了:
const momentFoo = require('moment-timezone').instance();
momentFoo.tz.setDefault('foo');
const momentBar = require('moment-timezone').instance();
momentBar.tz.setDefault('bar');
momentFoo.tz() === momentBar.tz() //false
并且对于每个时刻实例都有自己的本地配置。
这对于使用 Express 的应用程序也非常有用,您可以在其中为请求的持续时间创建一个 moment 实例,使用全局时区对其进行配置,并确保您的所有其余中间件都将使用正确的时区。
现在,我们必须在代码库中的 100 多个地方设置正确的时区,因为我们不能使用moment.tz.setDefault()
。
想法?
你可以做
import moment from 'moment-timezone';
export default moment().tz('foo');
import momentFoo from '../somewhere/moment-foo';
@isair它不太
Uncaught TypeError: Object(...) is not a function
当然,我们将在https://github.com/moment/momentjs.com获取文档 PR
@adamreisnz - 请在https://github.com/moment/moment-timezone 中为您的功能请求提交一张票
#684 究竟是如何解决这个问题的? 据我所知,这只是一个自述文件更新,以澄清当前的行为。
const estMoment = (...args) => moment(...args).tz('America/New_York')
console.log(estMoment().toDate())
console.log(moment().toDate())
而不是设置默认值; 我们可以有一个moment
各种时区(对于离。 estMoment
, mstMoment
, pstMoment
等)并使用它无处不在。 对于前estMoment('2020-08-12');
而不是moment('2020-08-12');
祝你好运...
最有用的评论
#684 究竟是如何解决这个问题的? 据我所知,这只是一个自述文件更新,以澄清当前的行为。