How to sort date with dd-MMM-yyyy hh: mm tt format in datatable

I am currently working on a datatable, I found that my sort column for the date did not work. here is my screenshot

datatable view

Here is my code

<table id="tbl" class="table table-small-font table-bordered table-striped">
  <thead>
    <tr>
      <th>&nbsp;</th>
      <th class="text-left">Dated</th>
      <th class="text-left">Day</th>
      <th class="text-center">Remarks</th>
      <th class="text-center">State</th>
      <th class="text-center"></th>
    </tr>
  </thead>
  <tbody>
    @{ IEnumerable
    <PublicHoliday> PublicHolidays = (IEnumerable
      <PublicHoliday>)ViewData["PublicHolidays"]; int Idx = 1; } @foreach (var i in PublicHolidays) {
        <tr>
          <td>@Idx</td>
          <td>@i.Dated.ToString("dd-MMM-yyyy hh:mm tt")</td>
          <td>@i.Dated.ToString("ddd")</td>
          <td>@Html.DisplayFor(x => i.Remarks)</td>
          <td>@i.ForStateName</td>
          <td><a data-toggle="tooltip" title="Delete" onclick="DeleteRecord(@i.Id);"><span class="glyphicon glyphicon-remove"></span></a></td>
        </tr>
        Idx++; }
  </tbody>
</table>
<script src="~/lib/jquery-ui-1.12.1/jquery-ui.min.js"></script>
<script src="~/js/jquery.dataTables.min.js"></script>
<script src="~/js/dataTables.bootstrap.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    var tbl = $('#tbl').DataTable({
      dom: "<'row'<'col-sm-6 col-xs-7'l><'col-sm-6 col-xs-7'f>>" + "rtip",
      order: [
        [0, "asc"]
      ],
      pagingType: "numbers",
      iDisplayLength: 50
    });
  });
</script>

the sort column does not work at all, and I cannot find any datatable plugin to use. anyone please help .. thanks in advance

+4
source share
3 answers

I'm not sure there is a plugin supporting date-dd-MMM-yyyy hh:mm tt format

So, I made changes to the plugin to support this format.

Here is the code for this. Download this piece of code after loading the plugindatatable

   (function() {

       var customDateDDMMMYYYYToOrd = function(date) {
         var dateTime = date.split(' '),
           dateObj = new Date(dateTime[0].replace(/-/g, ' ')),
           time = "00:00",
           type = "AM";
         if (dateTime.length > 1) { // if time part and am/pm part is available
           time = dateTime[1],
             type = dateTime[2];
         }

         var splitTime = time.split(":"),
           hours = type == "PM" ? Number(splitTime[0]) + 12 : Number(splitTime[0]),
           minutes = Number(splitTime[1]),
           seconds = 0,
           milliseconds = 0;
         return new Date(dateObj.getFullYear(), dateObj.getMonth(), dateObj.getDate(), hours, minutes, seconds, milliseconds);
       };

       // This will help DataTables magic detect the "dd-MMM-yyyy" format; Unshift
       // so that it the first data type (so it takes priority over existing)
       jQuery.fn.dataTableExt.aTypes.unshift(
         function(sData) {
           "use strict"; //let avoid tom-foolery in this function
           if (/^([0-2]?\d|3[0-1])-(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)-\d{4}/i.test(sData)) {
             return 'date-dd-mmm-yyyy';
           }
           return null;
         }
       );

       // define the sorts
       jQuery.fn.dataTableExt.oSort['date-dd-mmm-yyyy-asc'] = function(a, b) {
         "use strict"; //let avoid tom-foolery in this function
         var ordA = customDateDDMMMYYYYToOrd(a),
           ordB = customDateDDMMMYYYYToOrd(b);
         return (ordA < ordB) ? -1 : ((ordA > ordB) ? 1 : 0);
       };

       jQuery.fn.dataTableExt.oSort['date-dd-mmm-yyyy-desc'] = function(a, b) {
         "use strict"; //let avoid tom-foolery in this function
         var ordA = customDateDDMMMYYYYToOrd(a),
           ordB = customDateDDMMMYYYYToOrd(b);
         return (ordA < ordB) ? 1 : ((ordA > ordB) ? -1 : 0);
       };

     })();

(dd-mmm-yyyy). customDateDDMMMYYYYToOrd,

, , ,

   var tbl = $('#tbl').DataTable({
    dom: "<'row'<'col-sm-6 col-xs-7'l><'col-sm-6 col-xs-7'f>>" + "rtip",
    order: [[0, "asc"]],
    pagingType: "numbers",
    pageLength: 50,
    columnDefs: [
      { type: 'date-dd-mmm-yyyy', targets: 1 } //add this part
    ]   
});

, datatable

:

, ** *. datetime .

+1

02-Jan-2017 12:00 AM .. RFC2822, , , - type date:

columnDefs: [
  { targets: 1, type: 'date' }
]

, , , null, , ( , ):

columnDefs: [
  { targets: 1, 
    type: 'num',
    render: function(data,type) {
      if (type == 'sort') return Date.parse( data ).valueOf() 
      return data
    }
  }
]

. - data-sort

<td data-sort="@i.Dated.ToString()">@i.Dated.ToString("dd-MMM-yyyy hh:mm tt")</td>
+1

I use momentjs and lodash, he would like:

var records = [
    ["1", "28-Jan-2017 12:00 AM"],
    ["1", "28-May-2017 12:00 AM"],
    ["1", "28-Mar-2017 12:00 AM"]
];

records = _.map(records, record => {
    record.push(moment(record[1], "DD-MMM-YYYY hh:mm A").unix());
    return record;
});

$(document).ready(function() {
    $('#example').DataTable( {
        data: records,
        columns: [
            { title: "id" },
            { title: "date" },
            { title: "ts"}
        ],
        'columnDefs': [
            { 'orderData':[2] },
            {
              'targets': [2],
              'visible': false
            },
        ],
    });
});

$(document).ready(function() {
    $('#example').DataTable( {
        data: records,
        columns: [
            { title: "id" },
            { title: "date" },
            { title: "ts"}
        ],
        'columnDefs': [
                    { 'orderData':[2] },
                    {
                    'targets': [2],
                    'visible': false
                    },
                ],
    });
});

Here is jsFiddle

0
source

Source: https://habr.com/ru/post/1690593/


All Articles