mattpm
mattpm

Reputation: 1390

Formatting date using moment.js using locale rather than explicit format

Our dates from our date selector are in DD/MM/YYYY h:mm A format. Currently, we need to supply a format explicitly to moment.js in order to have this date correctly interpreted as follows:

var dateFormats = ['DD/MM/YYYY h:mm A'];
var tmp1 = moment(date, dateFormats).format('YYYY-MM-DD HH:mm');

Our preference would be to avoid hardcoding dateformats and instead be able to apply the locale as follows:

var locale = (window.navigator.userLanguage || window.navigator.language).toLowerCase();
moment.locale(locale);
var tmp1 = moment(date).format('YYYY-MM-DD HH:mm');

Currently, executing the following (after applying the locale above):

moment('15/12/2016 2:27 PM').format('YYYY/MM/DD h:mm A');

gives:

"2017/03/12 2:27 PM"

When it needs to give:

"2016/12/15 2:27 PM"

How can we achieve this?

Upvotes: 2

Views: 6810

Answers (1)

VincenzoC
VincenzoC

Reputation: 31502

If your input string has a locale specific format, you can use moment's localeData to parse it. Using longDateFormat(dateFormat); you can get localized format.

Here a working example using en-au locale:

moment.locale('en-au');
var input = '15/12/2016 2:27 PM';
var s = moment(input).format('YYYY/MM/DD h:mm A'); // Gives Deprecation warning
console.log(s); // Invalid date

// Get locale data
var localeData = moment.localeData();
var format = localeData.longDateFormat('L') + ' ' + localeData.longDateFormat('LT');
s = moment(input, format).format('YYYY/MM/DD h:mm A');
console.log(s); // 2016/12/15 2:27 PM
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.0/moment-with-locales.min.js"></script>

Upvotes: 5

Related Questions