【问题标题】:Moment.js date conversion is not working with DataTableMoment.js 日期转换不适用于 DataTable
【发布时间】:2019-02-20 16:43:32
【问题描述】:

我有一个 DataTable,其中包含格式如下的日期:"/Date(1185336000000)/"

在下面的代码中,我按照 DataTable 的文档集成了 Moment.js 以进行日期转换——要么我遗漏了某些东西,要么我的代码编写不正确。或两者兼而有之。

对此有什么想法吗?我相信部分问题在于function loadPH,但我不想删除它。

JS sn-p:

import $ from 'jquery';
import admissData from '../JSON/sk-admiss.json';
import DataTable from 'datatables.net';

import moment from 'moment';

function loadPH() {
    let admissText = admissData.d.results
    .filter(x => x.p_h_v !== "")
    .map(function(val) {
        return {
            "PH": val.p_v_h,
            "Stuff": val.stuff,
            ...
            ...
            "Date of Admission": val.dateofadmission,
            ... // ----- irrelevant info
        }
    })

    $.fn.DataTable.moment('MMM Do YY'); // ---- console error: "default.a.fn.DataTable.moment is not a function"
    $('#prohac-table').DataTable({
        columns: [
            { data: "PH" },
            { data: "Stuff" },
            ...
            ...
            { data: "Date of Admission" },
            ... // ----- irrelevant info
        ],
        columnDefs: [{
            type: 'date',
            targets: [4]
        }],
        data: admissText
    });

}

loadPH();

HTML sn-p:

<script src="index.js"></script>

    <script 
      src="https://code.jquery.com/jquery-3.3.1.slim.min.js" 
      integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>

    <script     
      src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>

    <script 
      src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.0/js/bootstrap.min.js" integrity="sha384-7aThvCh9TypR7fIc2HV4O/nFMVCBwyIUKL8XCtKE+8xgCgl/PQGuFsvShjr74PBp" crossorigin="anonymous"></script>

    <script 
      src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script>

    <script 
      src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>

    <script 
      src="//cdn.datatables.net/plug-ins/1.10.12/sorting/datetime-moment.js"></script>

【问题讨论】:

    标签: javascript jquery json datatable momentjs


    【解决方案1】:

    更新:我进行了一些挖掘,解决方案涉及使用 columnDefs

            { data: "x" },
            { data: "y" },
            { data: "z" },
            { data: "zz" },
            { data: "Date of Admission" }, // ----- target
            ...
               { data: "Classification" }
            ],
            columnDefs: [
                {"type":"unix","targets":4,"render": function(data) { 
                    return moment.utc(data, "x").format('MM/DD/YYYY')
                }}, // targets must be plural
            ],
    

    【讨论】:

      【解决方案2】:

      这是我将如何处理奇怪的日期格式"/Date(1185336000000)/",我假设它是一个以毫秒为单位的Unix时间戳。

      首先,从您的代码中删除该行:$.fn.DataTable.moment('MMM Do YY');

      然后,processStrangeDate()随意重命名它)将是一个检索 Unix 时间戳并使用 Moment.js 转换它的函数

      function parseDate(strangeDate){
        return moment(parseInt(strangeDate.split("(")[1])).format('MMM Do YY');
      }
      

      这是一个简单的演示:

      var strangeDate = "/Date(1185336000000)/";
      
      // A function to process that strange date format
      function processStrangeDate(strangeDate){
        return moment(parseInt(strangeDate.split("(")[1])).format('MMM Do YY');
      }
      
      // Processing example
      var strangeDate = "/Date(1185336000000)/";
      console.log(processStrangeDate(strangeDate));
      &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"&gt;&lt;/script&gt;

      以及如何在 DataTables 中使用它:

      // A function to process that strange date format
      function processStrangeDate(strangeDate){
        return moment(parseInt(strangeDate.split("(")[1])).format('MMM Do YY');
      }
      
      // Example in dataTables using columnDef
      $("#example").dataTable({
        data:[
          ["Line 1","/Date(1185336000000)/","/Date(1185336000000)/"]
        ],
        columnDefs:[
          {
            targets:2, render: function(data){  // Target is the column # zero-based
              return processStrangeDate(data);
            }
          }
        ]
      
      });
      <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
      <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.0/js/bootstrap.min.js" integrity="sha384-7aThvCh9TypR7fIc2HV4O/nFMVCBwyIUKL8XCtKE+8xgCgl/PQGuFsvShjr74PBp" crossorigin="anonymous"></script>
      <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script>
      <script src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
      <script src="//cdn.datatables.net/plug-ins/1.10.12/sorting/datetime-moment.js"></script>
      
      <!-- Above is your CDN calls untouched... I just added some CSS below -->
      <link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.19/css/jquery.dataTables.css" rel="stylesheet"/>
      
      <table id="example">
        <thead>
          <th>Something</th>
          <th>Strange Date</th>
          <th>Processed Date</th>
        </thead>
        <tbody>
        </tbody>
      </table>

      CodePen

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-09-28
        • 2014-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多