【问题标题】:Format Date to show "Today"/"Tomorrow" instead of Month-Day in JqxGrid格式化日期以在 JqxGrid 中显示“今天”/“明天”而不是月日
【发布时间】:2014-08-28 13:09:01
【问题描述】:

我们使用 jqxgrid 在屏幕上显示房间信息。为了便于阅读,我们尝试将日期格式化为“今天”或“明天”,而不是实际日期(今天或明天......)。

除了重新格式化为“今天”和“明天”之外,一切正常(网格显示了它应该显示的一切)。我们尝试使用 moment.js,但不知何故它不起作用。

这是我们的来源

 datatype: "json",
        datafields: [
            {name: 'title', type: 'string'},
            {name: 'room_name', type: 'string'},
            {name: 'room_number', type: 'string'},
            {name: 'start', type: 'date', format: "yyyy-MM-dd HH:mm"},
            {name: 'end', type: 'date', format: "yyyy-MM-dd HH:mm"},
            {name: 'email', type: 'string'},
            {name: 'comment', type: 'string'}

            ...

  $("#jqxgrid").jqxGrid(
        {
        columns: [
                {text: 'Raum #', dataField: 'room_number', width: 120},
                {text: 'Raum-Name', dataField: 'room_name', width: 340},
                {text: 'Von', dataField: 'start', width: 190, cellsalign: 'center', cellclassname: "startdate"},
                {text: 'Bis', dataField: 'end', width: 190, cellsalign: 'center', cellsformat: 'dd.MM'},
                ....

注意:网格单元“VON”中的输出如下所示:Thu Aug 28 2014 16:30:00 GMT+0200 (CEST)

如您所见,开始日期包含在 div 类 startdate 中。

我们尝试通过 javascript 重新格式化它:

$(document).ready(function() {
    function formatDate(date) {
        date.each(function(){
            var formattedDate = $(this).text();
            var d = moment(formattedDate);
            $(this).html( d.format("dddd, MMMM Do"));

        });
};

formatDate($('.startdate'));
});

当我们在 jqxgrid 之外的 div 上使用它时,这非常有效。但是,它在其中不起作用。有什么想法吗?

更新:这就是诀窍:

 window.setTimeout(function(){
            console.log($('.startdate div').innerHTML);
            formatDate($('.startdate div'));
        }, 2000);

正如 gp 正确说明的那样,稍后会生成 div。无论如何,是否有更好的解决方案?

【问题讨论】:

  • 可能当您调用 formatDate 时,尚未生成 div,因此 $('.startdate') 不会选择那些 div。你检查了吗?
  • 是的,我刚刚查过了,你是对的。 window.setTimeout(function(){ console.log($('.startdate div').innerHTML); formatDate($('.startdate div')); }, 2000); 成功了。但是没有更好的解决方案吗?
  • 尝试在 $("#jqxgrid").jqxGrid() 方法调用之后调用 formatDate。

标签: javascript date momentjs jqxgrid


【解决方案1】:

您可以将格式化调用添加到网格的就绪函数中:

$("#jqxgrid").jqxGrid(
    {
        columns: [ ... ],
        ready: function() {
            formatDate($('.startdate'));   
        },
        ....
    });

【讨论】:

  • 就是这样!谢谢好心的先生!
【解决方案2】:

在调用 formatDate 之前,您需要确保在网格中生成了 div (.startdate)。

最好使用 jqxgrid 的“初始化”事件。

$('#jqxgrid').on('initialized', function () {
    formatDate($('.startdate div'));
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    相关资源
    最近更新 更多