Moment-Timezone is using default locale after global Moment locale is set

Viewed 8742

I'm building an application written in Typescript which uses features from both Moment.js and moment-timezone. I need the date and timestamps within the application localized so in the main app.ts file I set moment's locale using the language of the device.

UPDATE: here is a gist of the sample files with additional comments https://gist.github.com/spstratis/fa853f9750a095d4acd0d1196a285be9

app.ts

import * as moment from 'moment/min/moment-with-locales';

let language = appUtil.getPhoneLanguage();

moment.locale(language);

// the expected locale is printed
console.log("Moment Locale = " + moment.locale());

The issue is, in this utilities module when I import moment-timezone, it is defaulting to 'en' locale even though I have set moment's locale globally in the main app.ts file.

Below are two of my utility methods, how can I localize the relative date strings and months if moment-timezone is defaulting them to 'en'?

I tried adding the .locale(locale) to the moment methods but that didn't change anything. If I imported moment instead of moment-timezone that worked for some of the methods but failed on any of them which needed to use the timezone utilities.

date-util.ts

import * as moment from 'moment-timezone';

export function dateRelativeTime(value): string {
  let timezoneId = appCache.getTimezoneId();
  let localTime = _getLocalUtcDateString(value, timezoneId);
  let dateMoment = moment(localTime, "MM/DD/YYYY hh:mm:ss A");
  let formatedDate = dateMoment.tz(timezoneId).fromNow();

  return formatedDate;
};

export function localizedMonths(): ValueList {
  let m = moment("2016");
  let months = new ValueList([]);
  for (var i = 0; i < 12; i++) {
    months.push({ ValueMember: [i + 1], DisplayMember: m.month(i).format('MMMM') });
  }

  return months;
};
4 Answers

I had the same issue in Typescript. I wanted to use moment-timezone to set timezone to Europe/Brussels and set locale to Belgian Dutch and I solved it like this:

import 'moment/locale/nl-be';
import * as momentTZ from 'moment-timezone';
momentTZ.locale("nl-be");
momentTZ.tz.setDefault("Europe/Brussels");

Now use momentTZ if you want to use moment in your project, like this f.e.

const exampleDate = momentTZ().format('dddd D MMMM');

I'm not sure why but I suddenly had the same issue.
It seems like you need some extra config when using moment and moment-timezone with locale setting.

Here is the minimum setup when you use only one locale.

import 'moment/locale/ja' // or whatever locale you want
import moment from 'moment'
import memontTZ from 'moment-timezone'
mementTZ.defineLocale('ja', moment.localData()._config)

I belive you can configure multiple locales by following the example below.
Ref: https://github.com/moment/moment-timezone/issues/647#issuecomment-439600573

Related