While the accepted answer does the job by manipulating the pre-defined localized formats Moment provides, there's another way that Moment allows you to extend its localized configuration that may be more suitable in some situations.
If you open up one of the localization files in the npm module, like /moment/locale/de.js
,
you'll see a list of localized date formats that looks like this:
longDateFormat : {
LT: 'HH:mm',
LTS: 'HH:mm:ss',
L : 'DD.MM.YYYY',
LL : 'D. MMMM YYYY',
LLL : 'D. MMMM YYYY HH:mm',
LLLL : 'dddd, D. MMMM YYYY HH:mm'
},
This will give you a good starting point and clue at how to localize for each locale you support. For example, German places the day with a period before the month, where in English, The month comes before the day.
You can then copy and tweak the format you want, by extending the configuration at initialization:
// Update configs with custom date formats per language after
// moment locales are loaded (LMD is a custom format here)
moment.updateLocale('en', { longDateFormat: { LMD: 'MMMM D' } });
moment.updateLocale('de', { longDateFormat: { LMD: 'D. MMMM' } });
// repeat with culturally-correct formatting for other locales you support
function changeLang(value){
moment.locale(value);
// Retrieve stored custom format
var format = moment.localeData().longDateFormat('LMD');
var res = moment().format(format);
$("#result").html(res);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>
<select onchange="changeLang(value)">
<option value="en">EN</option>
<option value="de">DE</option>
</select>
<div id="result"></div>
You could also forego extending the configuration, and keep your custom formats in a custom data structure something like this:
var MOMENT_FORMATS = {
LMD: {
en: 'MMMM D',
de: 'D. MMMM'
}
};
moment().format(MOMENT_FORMATS.LMD[moment.locale()])
en-CA
will trigger it. – Goldsworthyen-CA
– Parasang