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;
};
You are importing moment wrong. Don't do this:
import * as moment from 'moment/min/moment-with-locales';
Just do this:
import * as moment from 'moment';
It will load the individual locales as you use them (on Node.js) and you will then be sharing the same moment dependency that moment-timezone uses, so your global locale will carry through.