【发布时间】:2017-10-15 21:24:14
【问题描述】:
我将一些 JSON 数据传递到我的视图中,其中包含许多内容,包括 DateTime。我目前在 Controller 中将其编码为 ISO 格式,因此我将 2017-10-13T23:21:00 作为我的日期,但我不知道如何将它带到更友好的 10/13/17 11:21pm。
目前它作为 javascript 脚本的一部分在视图中呈现。具体部分是:
var template = "<tr><td>${DateTime}</td><td>${OtherStuff}</td></tr>"
我试过了
var dt = new Date("${DateTime}")
var template = "<tr><td>" + dt + "</td><td>${OtherStuff}</td></tr>"
没有成功(而不是预期的输出,我收到了“无效日期”)。我收到的错误让我认为我走在正确的道路上,只是稍微偏离了一点。
添加一些附加代码以防万一
这是全部的一部分
$(function () {
var data = @Html.Raw(Json.Encode(Model));
var renderTable = function (success, error) {
var dt = new Date("${DateTime}");
var template = "<tr><td>" + dt + "</td><td>${OtherStuff}</td></tr>"
if (success) {
$("#table tbody").empty();
$($.ig.tmpl(template, ds.dataView())).appendTo("#table tbody");
} else {
alert(error);
}
}
//This code creates an $.ig.DataSource from JSON data
var ds = new $.ig.DataSource({
type: "json",
dataSource: data,
callback: renderTable
});
// Binds to the underlying data
ds.dataBind();
});
我相信我现在看到了问题,模板就是这样,一个模板,所以我无法格式化稍后将填充的占位符变量。但是我该怎么做呢?
【问题讨论】:
-
moment.js 之类的库有助于处理日期并减少大量手动编码
-
试试jQuery日期格式github.com/phstc/jquery-dateFormat我认为“MM/dd/yyyy hh:mm”是am/pm格式
-
这两个看起来都很简洁和方便,但我对如何在上面的上下文中使用它们还不是很清楚。
标签: javascript jquery json asp.net-mvc datetime