Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moment get date formatted on locale

From the moment docs setting format as l returns in format "M/D/YYYY". Is there a way to get the date in just D/M or M/D format depending on locale? Here is the code i have right now.

var locale = window.navigator.userLanguage || window.navigator.language;
moment.locale(locale);
var momentTime = moment(d);
console.log(momentTime.format('l'));

For instance if the locale is French then the date should be returned in D/M format and if the locale is english-us then the date should be returned in M/D format automatically.

like image 656
meteor Avatar asked Dec 19 '22 10:12

meteor


1 Answers

One way to do what you need is getting localized longDateFormat and then remove the year part with a regular expression.

Here a working example that uses localeData and then longDateFormat. I'm not sure that it will work for each locale, but it gives the right result for fr and en-us (and probably many others).

var locale = window.navigator.userLanguage || window.navigator.language;
moment.locale(locale);

// Get locale data
var localeData = moment.localeData();
var format = localeData.longDateFormat('L')
// Remove year part
format = format.replace(/.YYYY/, ''); 

var momentTime = moment();
console.log(momentTime.format(format));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>
like image 177
VincenzoC Avatar answered Dec 28 '22 23:12

VincenzoC