简体   繁体   English

将数据库字段另存为YYYY-MM-DD; 需要显示和排序为DD-MM-YYYY

[英]Saved db field as YYYY-MM-DD; need display and sort as DD-MM-YYYY

I have a MySQL date field that is saved, for example, as 2015-06-26 and I need to display and sort it in a datatable as 26-06-2015 . 我有一个MySQL日期字段,例如,保存为2015-06-26 ,我需要在数据表中将其显示和排序为26-06-2015

I think that "it's not rocket science" but I've read a bunch of articles without understand where I should start from (server-side, some plugin or not, moment, etc). 我认为“这不是火箭科学”,但我读了很多文章,却不知道我应该从哪里开始(服务器端,是否有插件,片刻等等)。

This is my debug code: debug.datatables.net/aninog 这是我的调试代码: debug.datatables.net/aninog

This is JS code: 这是JS代码:

    var dettagli = []; 
    var table = $('#tabellaDati').DataTable( {
        "stateSave": true,
        "language": {
            "sEmptyTable":     "Nessun dato presente nella tabella",
            "sInfo":           "Vista da _START_ a _END_ di _TOTAL_ elementi",
            "sInfoEmpty":      "Vista da 0 a 0 di 0 elementi",
            "sInfoFiltered":   "(filtrati da _MAX_ elementi totali)",
            "sInfoPostFix":    "",
            "sInfoThousands":  ",",
            "sLengthMenu":     "Visualizza _MENU_ elementi",
            "sLoadingRecords": "Caricamento...",
            "sProcessing":     "Elaborazione...",
            "sSearch":         "Cerca:",
            "sZeroRecords":    "La ricerca non ha portato alcun risultato.",
            "oPaginate": {
                "sFirst":      "Inizio",
                "sPrevious":   "Precedente",
                "sNext":       "Successivo",
                "sLast":       "Fine"
            },
            "oAria": {
                "sSortAscending":  ": attiva per ordinare la colonna in ordine crescente",
                "sSortDescending": ": attiva per ordinare la colonna in ordine decrescente"
            }                   
        },
        "data": datiTabella,
        "columns": [
            {
                "sWidth": "8%",
                "className":      'details-control',
                "orderable":      false,
                "data":           null,
                "render": function(data, type, row, meta) {
                    return  '<a class="btn btn-xs" href="incarico_form.php?action=edit&id='+data.id+'&pageFrom=<?=pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME ); ?>" title="Modifica"><span class="glyphicon glyphicon-edit"></span></a>'+
                            '<a class="btn btn-xs delete-object" delete-id="'+data.id+'" title="Elimina"><span class="glyphicon glyphicon-trash"></span></a>'+
                            '<a class="btn btn-xs" href="" id="mostraDettaglio" title="dettaglio"><span class="glyphicon glyphicon-folder-open"></span></a>';
                }
            },
            { "data": "id" },
            { "data": "protocollo" },
            { "data": "nomeAssicurato"},
            { "data": "sinistro"},
            { "data": "tipoEvento"},
            { "data": "dataSinistro"},
            { "data": "dataSopralluogo"},
            { "data": "dataIncarico"},
            { "data": "idStatoPratica"},
            { "data": "idStatoPerizia"},
            { "data": "nomeIncaricato"},
            { "data": "dataScadenza"},

        ],

        "order": [[1, 'asc']],
        "initComplete": function( settings, json ) {

            function format ( d ) {
                // `d` is the original data object for the row
                // carica il template del dettaglio
                // usando JsRender
                $.ajax ({
                    async: false,
                    type: "POST",
                    url: "incaricodetail.html",
                    cache: false,
                    success: function(data){
                        templateHtml = data; 
                    }
                });

            var template = $.templates(templateHtml);
            var htmlOutput = template.render(d);
            return htmlOutput;
            }
            // carica i dati formattati in html nell'array dettagli
            // for (i=0; i < this.api().data().length; i++) {
                // data = this.api().row(i).data();
                // dettagli[i] = format(data);
            // }

            // Aggiungo un listener come 'delegato' in modo che possa funzionare anche su elementi della pagina aggiunti in un secondo momento tramite salto ad altra pagina o filtro
            $('#tabellaDati tbody').on('click', '#mostraDettaglio', function () {
                // alert("click");
                var tr = $(this).closest('tr');
                var row = table.row( tr );
                var span = $(this).find("span");

                if ( row.child.isShown() ) {
                    // This row is already open - close it
                    row.child.hide();
                    span.removeClass("glyphicon glyphicon-folder-close").addClass("glyphicon glyphicon-folder-open");   
                }
                else {
                    // Open this row
                    // row.child(dettagli[row.index()]).show(); //carica dati da array dettagli
                    row.child( format(row.data())).show(); //carica dati da ajax
                    span.removeClass("glyphicon glyphicon-folder-open").addClass("glyphicon glyphicon-folder-close");   
                }
                return false;
            });             
        },
    });

The field with date is dataIncarico 日期为dataIncarico的字段

This is probably best done using momentjs. 最好使用momentjs完成此操作。 In your column definition add a render and a type like this: 在您的列定义中添加一个渲染器和一个像这样的类型:

{ 
    "data": "dataIncarico",
    "type": "date-uk",
    "render": function(data){
        return moment(data).isValid() ? moment(data).format("DD/MM/YYYY") : "";
    }
}

That takes care of the formatting and also tells datatables to use a different function to order the data: 这样既可以设置格式,又可以告诉数据表使用其他函数对数据进行排序:

$.extend($.fn.dataTableExt.oSort, {
    "date-uk-pre": function (a){
        if(moment(a, "DD/MM/YYYY").isValid()){
            return parseInt(moment(a, "DD/MM/YYYY").format("X"), 10);
        }else{
            return 0;
        }
    },
    "date-uk-asc": function (a, b) {
        return a - b;
    },
    "date-uk-desc": function (a, b) {
        return b - a;
    }
});

If you're looking to search using the server-side script your'll need to input the date in YYYY-MM-DD format or look at using a date input. 如果要使用服务器端脚本进行搜索,则需要以YYYY-MM-DD格式输入日期或使用日期输入来查看。

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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