Home > Net >  How to convert moment.js date format 'LLL' to 'YYYY-MM-DD'
How to convert moment.js date format 'LLL' to 'YYYY-MM-DD'

Time:01-13

How can i change format of moment.js date? I use locales format ('LLL') in datatables columnDefs render and trying to filter date column with external filter inputs. When i format input value with 'LLL', logical operators doesn't work correct. So maybe if i convert column data, it will work. Theese are my codes:

"render": function (data) {
                        var locale = lang;
                        return (moment(data).isValid()) ? moment(data).locale(locale).format("LLL") : "-";

and filtering is:

$.fn.dataTableExt.afnFiltering.push(
            function (oSettings, aData, iDataIndex) {
                var filterstart = $('#start').val();
                var filterend = $('#end').val();
                var datecolumn = 5;
                var tabledatestart = aData[datecolumn];
                var tabledateend = aData[datecolumn];

                var locale = lang;
                filterstart = (moment(filterstart).isValid()) ? moment(filterstart).locale(locale).format('LLL') : "";
                filterend = (moment(filterend).isValid()) ? moment(filterend).locale(locale).format('LLL') : "";

                if (filterstart === "" && filterend === "") {
                    return true;
                }
                else if ((filterstart==tabledatestart || filterstart<tabledatestart) && filterend === "") {
                    return true;
                }
                else if ((filterstart==tabledatestart || filterstart>tabledatestart) && filterstart === "") {
                    return true;
                }
                else if ((filterstart==tabledatestart || filterstart<tabledatestart) && (filterend==tabledateend || filterend>tabledateend)) {
                    return true;
                }
                return false;
            }
        );

CodePudding user response:

Make sure to use moment with locales and set the locale before parsing the date.

moment.locale('tr_TR');

console.log(
  moment('6 Ocak 2022 12:45', 'LLL').format('YYYY-MM-DD')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment-with-locales.min.js"></script>

I'm pretty sure that the locale needs to be set first before parsing, as the following returns 'Invalid Date':

console.log(
  moment('6 Ocak 2022 12:45', 'LLL').locale('tr_TR').format('YYYY-MM-DD')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment-with-locales.min.js"></script>

  •  Tags:  
  • Related