【问题标题】:How to JS Date Format如何 JS 日期格式
【发布时间】:2021-04-17 02:23:24
【问题描述】:

我在这个项目中使用 Laravel 8 和 Bootsrap。我已经尝试在 Laravel 中使用 Carbon 解决这个问题,但问题仍然存在。

所以我认为可能是 JS 脚本的问题,但我不知道 JS 有这么深。我真的需要这个问题的帮助。

我的问题是如何在 JS 中更改日期格式,我希望更改为 DD/MM/YYYY 格式。

JS 脚本

<script>
$(function() {
    $('#kategoris-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: 'kategori/json',
        columns: [
            { data: 'id', name: 'id' },
            { data: 'nama', name: 'nama',
                fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
                    $(nTd).html("<a href='/kategoris/"+oData.id+"'>"+oData.nama+"</a>");
                }
            },
            { data: 'updated_at', name: 'updated_at'},
        ]
    });
});
</script>

我的表格视图

【问题讨论】:

  • 你能分享你显示日期的代码吗?你用的是Vue之类的前端框架吗?
  • 有什么问题?你能edit这个问题澄清一下吗?
  • @Andrew 我已经向它展示了代码,仅在 JS 代码中。我这样做了,而且我使用 Bootstrap。
  • @andrewjames 好的。

标签: javascript laravel datatable


【解决方案1】:

将此变量添加到模型类:

protected $casts = [
    'updated_at' => 'datetime:m/d/Y'
];

这将更改日期时间格式,并在您通过 eloquent 检索数据时反映出来。

【讨论】:

  • 谢谢,很高兴找到这个信息。 :)
  • 很高兴能帮上忙
【解决方案2】:

您可以尝试注册editor 并使用moment.js。像这样的:

var editor; // use a global for the submit and return data rendering in the examples

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

    editor = new $.fn.dataTable.Editor( {
        ajax: 'kategori/json',
        table: '#kategoris-table',
        fields: [ {
                label:  'Updated at:',
                name:   'updated_at',
                type:   'datetime',
                def:    function () { return new Date(); },
                format: 'DD/MM/YYYY',
                fieldInfo: 'Formatted date'
            }
        ]
    } );

    $('#kategoris-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: 'kategori/json',
        columns: [
            { data: 'id', name: 'id' },
            { data: 'nama', name: 'nama',
                fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
                    $(nTd).html("<a href='/kategoris/"+oData.id+"'>"+oData.nama+"</a>");
                }
            },
            { data: 'updated_at', name: 'updated_at'},
        ]
    });
});

请参阅此示例,其中包含您需要在示例末尾加载的其他库:https://editor.datatables.net/examples/dates/formatting.html

PS - 我试图在我的答案中包含这些库以防链接断开,但当我这样做时,我收到消息“我的帖子中似乎有代码格式不正确”,我似乎无法让它与格式化链接一起工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多