moment locale not set correctly

2019-07-22 12:47发布

问题:

We're trying to find a problem with tests that use moment.js and fail when run on a server in Arizona but succeed when run locally here in the UK. We manually set the locale before creating a moment and can see that the local 'en-gb' is installed.

This fiddle highlights what I think the problem is (Need to set computer to Arizona Time zone first!) https://jsfiddle.net/2ve10ax4/

moment.locale('en-gb');
console.log(moment.locale());
// en-gb
console.log(moment('2016-05-01T00:00:00+00:00').format()); 
// 2016-04-30T17:00:00-07:00

I'm expecting to see the date formatted with respect to 'en-gb' locale but it shows it with respect to Arizona time. Am I missing something?

回答1:

Locale and timezone are orthogonal things. A locale does not specify a timezone unambigously. You need to set your timezone separately. You can use Momemt Timezone, and then you can use e.g.

.tz('Europe/London')


回答2:

By setting moment.locale('en-gb') you have specified a locale/language (brittish-english), not a timezone.

To specify a timezone you need to include the Moment.js Timezone library in your project, and then do something like:

console.log(moment('2016-05-01T00:00:00+00:00').tz('America/Phoenix').format());

The above will give you the timezone for Arizona.



回答3:

After reading more I believe parseZone is the correct solution, given that I am already including Time Zone information in the date string.

console.log(moment.parseZone('2016-05-01T00:00:00+00:00').format());