Datatables – convert from Mysql data: string to date object with moment.js

I have date field as string (Text type) in mysql column called "date_fld".

It is in string format in mysql column, which looks like: 31.12.2021

Using PHP and JS / moment.js, I would want to convert this string format to date object to sort the DataTables header by actual date.

I am not sure, how to do that?

## Fetch records
      $this->db->select('*');
      $records = $this->db->get('data2')->result();

      $data = array();

      foreach($records as $record ){
         
          $data[] = array( 
            "#"=>$record->id,
            "Date"=>$record->date_fld
          ); 
      }

      ## Response
      $response = array(
          "draw" => intval($draw),
          "iTotalRecords" => $totalRecords,
          "iTotalDisplayRecords" => $totalRecordwithFilter,
          "aaData" => $data
      );

      return $response; 
    }

DataTables:

$(document).ready(function(){
        $.fn.dataTable.moment('DD.MM.YYYY');
...

{ data: 'date_fld',
    render: function (data, type, row) {
      return moment(new Date(data)).format('DD.MM.YYYY');
    }
}

104 thoughts on “Datatables – convert from Mysql data: string to date object with moment.js”

  1. Fantastic beat ! I wish to apprentice while you amend
    your site, how can i subscribe for a blog web site?

    The account aided me a acceptable deal. I had been a little bit acquainted of this your broadcast offered
    bright clear idea

    Reply
  2. Just wish to say your article is as amazing.
    The clearness for your post is just cool and i can assume you are knowledgeable on this subject.
    Fine along with your permission allow me to take hold of your RSS feed
    to stay up to date with coming near near post. Thank
    you one million and please carry on the rewarding work.

    Reply
  3. Thanks for any other informative web site. Where else may
    just I am getting that type of information written in such a perfect means?
    I’ve a mission that I am just now working on, and I have been at the look out for such information.

    Reply
  4. Today, while I was at work, my sister stole my apple ipad and tested to see if it can survive
    a forty foot drop, just so she can be a youtube sensation. My iPad is
    now broken and she has 83 views. I know this
    is entirely off topic but I had to share it with someone! scoliosis surgery https://0401mm.tumblr.com/ scoliosis surgery

    Reply
  5. Hi, i read your blog occasionally and i own a similar one and i was just wondering if you get a lot of spam feedback?

    If so how do you reduce it, any plugin or anything you can suggest?
    I get so much lately it’s driving me mad so any support is very much appreciated.

    Reply