Having dates in different cultures (e.g. 19.10.2020 (German) 2020/10/19 (English)), I need to standardize the format as en-US (YYYY-MM-DD) when saving to the database. This is the approach I've taken:
// Function to convert any date locale (e.g. fr, de, ja, sv, nb) to en-US locale for database storage
reverseDateToEnLocale(date: string, format?: string) {
var locale = moment();
locale.locale(this.locale); // Setting the locale to fr, zh, de, en, etc.
if (!format) { format = "YYYY-MM-DD"; } // Desired format for database storage
var localeFormat = moment.localeData().longDateFormat('L'); // Getting the current moment locale date format
return moment(date, localeFormat).format(format); // Convert the format to en-US
}
However, when I include the following in the code:
var locale = moment();
locale.locale(this.locale);
console.log(moment().locale()); // Always returns the en locale
I don't want to modify the global moment locale setting. I only want the function to use a specific locale for converting to the desired English date format.
This code snippet works correctly with German dates but has issues with Chinese dates. I'm unsure what might be missing.
When passing 'zh' as the locale, the moment locale is not being set, resulting in an incorrect format being returned.
I've also attempted setting the locale using the following approach from https://momentjs.com/docs/#/i18n/:
moment.locale('en'); // Default to English locale
var localLocale = moment();
localLocale.locale('fr'); // Setting this instance to use French
localLocale.format('LLLL'); // Sunday, July 15 2012 11:01
moment().format('LLLL'); // Sunday, July 15 2012 11:01 AM
Unfortunately, this approach is not resolving the issue. Can you help me identify what might be wrong?