简体   繁体   中英

Moment.js Invalid date message

Im exploring moment.js with Datatables, and its really good for showing the date in the format that I want but there is a problem that i have with the data that I am converting. If the date is not valid it shows the message INVALID DATE, wihch is good but not what I really want. Is it possible to, insted of showing "Invalid Date" message, show what was in there originally? Like if it is not a date I want to see what it is, not that message.

Thanks!

EDIT: Thanks for your help guys! I have done this for the datatable "aoColumns":

{     "mData": "APE",
      "render": function(mData){
            if(mData != null){
                if(moment(mData).format("DD/MM/YYYY")== 'Invalid date')
                    {
                        return mData;                       
                    }
                else
                    {
                    return moment(mData).format("DD/MM/YYYY");
                    }
            }                               
                               },
        sDefaultContent: ''},
moment.updateLocale(moment.locale(), { invalidDate: "ur msg or NaN/null" });

Depending on how you've implemented Moment.js, you could simply check the return value from moment? For example

var prettyDate = moment()...;

if(prettyDate != 'Invalid date') {
    // set your date
}

 var dateStr = "aw 2017-06- awd 09 10:05:21.0"; //var dateStr = "a2017-06-09 10:05:21.0"; if(moment(dateStr, moment.ISO_8601).isValid()){ alert("Valid Date: " + moment(dateStr).format('MM/DD/YYYY')); } else { alert("Invalid Date: " +dateStr); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script> 

Try creating your own function where you check if the date is valid or not, see moment validation and if it is not valid return the original data for the message.

Update: Please see this post for extra explanation on the code snippet

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM