【问题标题】:jQuery dataTables editor plugin DateTime format issuejQuery dataTables 编辑器插件 DateTime 格式问题
【发布时间】:2018-06-29 00:39:47
【问题描述】:

我正在为一个站点使用 EF6 + MVC。 dataTables 编辑器用于 UI。一个表有一个字段“开始日期”。它是 SQL Server 中的日期时间类型。

在我尝试编辑“StartDate”值之前它工作正常。从浏览器调试中,我可以看到从后端发送到 UI 的 JSON 是时间戳格式,即 /Date(1541923200000)/ 。

在 dataTables 中,我将其转换为正确的本地日期时间格式,以便正确显示。

但是,我不知道如何在编辑器插件中执行此操作。它总是显示 /Date(1541923200000)/ 。

我使用的代码是:

editorAdvertisement = new $.fn.dataTable.Editor({
    ajax: '/APN/GetAdvertisementData',

    table: "#tblAdvertisements",
    fields: [{
        label: "StartDate",
        name: "AdvStartDate"
        , type: "datetime"
        , format: 'MM\/DD\/YYYY h:mm a'
    }, {
        label: "Deadline",
        name: "AdvDeadline"
        , type: "datetime"
    }, {
        label: "TitleOfAdv",
        name: "TitleOfAdv"
    }, {
        label: "ListPrice",
        name: "ListPrice"
    }
    ]
});

var tbl = $('#tblAdvertisements').DataTable({
    pageLength: 10,
    dom: '<"html5buttons"B>lTfgitp',
    ajax: '/APN/GetAdvertisementData'
    ,
    columns: [
        {
            data: "AdvStartDate", name: "AdvStartDate"
            , type: "datetime"
                , render: function (value) {
                    var r = convertDate(value);
                    return r;
                }
            , "autoWidth": true
        },
        {
            data: "AdvDeadline", name: "AdvDeadline"
            , type: "datetime"
            , render: function (value) {
                var r = convertDate(value);
                return r;
            }
            , "autoWidth": true
        },
        { data: "TitleOfAdv", name: "TitleOfAdv", "autoWidth": true },
        {
            data: "ListPrice", name: "ListPrice", "autoWidth": true
            , render: $.fn.dataTable.render.number(',', '.', 0, '$')
        }
    ],
    order: [1, 'asc'],
    select: {
        style: 'os',
        selector: 'td:first-child'
    },
    buttons: [
        { extend: "create", editor: editorAdvertisement }
        , { extend: "edit", editor: editorAdvertisement }
        , { extend: "remove", editor: editorAdvertisement }

    ]
    , select: true
    , searching: false
    , paging: false

});

在控制器中

[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult GetAdvertisementData()
{
    var request = HttpContext.Request.Form;
    var settings = Properties.Settings.Default;

    using (var db = new Database(settings.DbType, settings.DbConnection))
    {
        var response = new Editor(db, "Advertising", new[] { "AdvertisingID" })
            .TryCatch(false)
            .Model<Advertising2>()
            .Field(new Field("AdvStartDate")
                .Validator(Validation.DateFormat(
                    "MM/dd/yyyy",
                    new ValidationOpts { Message = "Please enter a date in the format MM/dd/yyyy" }
                ))
                .GetFormatter(Format.DateTime("yyyy-MM-dd HH:mm:ss", "MM/dd/yyyy"))
                .SetFormatter(Format.DateTime("MM/dd/yyyy", "yyyy-MM-dd HH:mm:ss"))
            )
            .Field(new Field("AdvDeadline")
                .Validator(Validation.DateFormat(
                    "MM/dd/yyyy",
                    new ValidationOpts { Message = "Please enter a date in the format MM/dd/yyyy" }
                ))
                .GetFormatter(Format.DateSqlToFormat("MM/dd/yyyy"))
                .SetFormatter(Format.DateFormatToSql("MM/dd/yyyy"))
            )

            .Field(new Field("TitleOfAdv"))
            .Field(new Field("ListPrice"))

            .Process(request)
            .Data();

        return Json(response, JsonRequestBehavior.AllowGet);
    }
}

经过长时间的搜索,我无法弄清楚。有人有同样的问题吗?有什么解决办法吗?

【问题讨论】:

  • var r = convertDate(value); => 我在任何地方都看不到convertDate 函数包含的内容,你能提供吗? /Date(xxxxxxxxxxxxx)/ 格式称为 DateTime 对象值,以毫秒为单位表示为字符串。
  • 这是一个将时间戳转换为yyyy-MM-dd的函数,但它只在dataTable中正确显示,而不是在编辑器中。

标签: c# jquery asp.net-mvc datetime datatables


【解决方案1】:

查看 moment.js (https://momentjs.com),下载 moment-with-locales.js 并将其添加到 BundleConfig.cs 中的 ScriptBundle。

然后,您可以在数据表的 javascript 代码中以正确的日期/时间格式呈现列,如下所示。注意:我的语言环境是“pt”(葡萄牙)。日期列呈现为 dd/mm/yyyy hh:mm(再次请参阅 https://momentjs.com 中的格式选项)。

"columns": [
        { "data": "OriginName" },
        { "data": "SmsID" },
        { "data": "DestinationNumber" },
        {
            "data": "SMSDeliveryDate",
            "render": function (data) {
                var re = /-?\d+/;
                var m = re.exec(data);
                var d = new Date(parseInt(m[0]));
                moment.locale('pt');
                var m = moment(d).format('L LTS');
                return m;
            }
        },
        { "data": "SmsStateDesc" }
    ],

希望这些信息有用。我也被这个困住了几个小时......

何塞

【讨论】:

    【解决方案2】:

    我遇到了同样的问题,最终在Editor forum上找到了答案。

    如果您使用 fiddler(查看会发生什么的好工具),您 看到 JSON 有你得到的这种格式。如果您查看代码 视觉工作室在传递之前表达并捕捉你得到的东西 JSON 您会看到类似“{12/12/2012 12:12}”的内容。所以实际上 原因是 JSON。

    重构为您的第一列中的要点,它应该是这样的。

    这种方法毫无问题地解决了我的问题。此版本旨在将空日期呈现为空白,否则按照指示进行格式化。 (更新:再次重构了答案,发现第二天早上格式化的代码没有按预期运行。)

    { 
       data: "AdvStartDate", 
       render: function (data, type, full) {
              if (data != null) {
                     var dtStart = new Date(parseInt(data.substr(6)));
                     return dtStart.toLocaleDateString();
              } else {
                     return "";
              }
       }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-06
      • 1970-01-01
      • 2010-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多