Skip to content
Advertisement

How do I change the date format?

This is my js function to fetch data from database. The data is being dynamically appended data to my modal popup from the js page. Currently the date format shown, is “2018-06-09 15:43:44″(as stored in database). I wish to change the date format that is being displayed to dd-MMM-YYYY. Is there a way to achieve this?

function fetch(url, id) {
    $.ajax({
        type: 'GET',
        url: url + id,
        headers: {
            'X-CSRF-TOKEN': $(`meta[name='_token']`).attr('content')
        },
        success: function (r) {
            let data = r;
//json value passed from controller in obj
            data = data.obj;
            let rows = '';
            $(data).each(function (index, row) {
                rows += `
                   <tr>
                            <td>${row.company_name}</td>
                            <td>${row.created_at}</td>
                   </tr>
            `;
            })
            $('.modalPage').html(rows);
        }
    });
}

Advertisement

Answer

You can easily override the default time format from the model but if you don’t want to do that you can also define your own function in Javascript and use that function to convert the format.

You can use this

var my_date_format = function (input) {
   var d = new Date(Date.parse(input.replace(/-/g, "/")));
   var month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 
   'Nov', 'Dec'];
   var date = d.getDay().toString() + " " + month[d.getMonth().toString()] + ", " + 
   d.getFullYear().toString();
   return (date);
}; 

and then call this function when the success method runs. like this.

success: function (r) {
        let data = r;
//json value passed from controller in obj
        data = data.obj;
        let rows = '';
        $(data).each(function (index, row) {
            rows += `
               <tr>
                        <td>${row.company_name}</td>
                        <td>${my_date_format(row.created_at)}</td>
               </tr>
        `;
        })
        $('.modalPage').html(rows);
    }
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement