2010-12-03 38 views
11

我刚开始使用jQuery Templates作为我的JavaScript模板引擎。我的问题是,我怎么能格式化表格的日期(从ASP.NET的Json的ActionResult返回):如何使用jQuery模板格式化日期/时间?

/Date(1288709830000)/ 

我试着做以下几点:

{{= $.format(new Date(parseInt(comment.DateCreated.substr(6))), 'd')}} 

注意上面使用了新的jquery全球化插件添加$.format方法。另外请注意,{{= comment.DateCreated }}是说${comment.DateCreated}长手。

我真的很感激,如果你可以帮忙。

+0

你有什么期望?究竟发生了什么? – jfar 2010-12-03 01:17:58

+0

我不会推荐使用jQuery或JavaScript进行模板化,如果你问我,这只是一个大的灾难 - 尝试在MVC视图/服务器级别做模板。 – 2010-12-03 03:19:29

回答

2

这确实有效。我使用的是Microsoft CDN上托管的测试版本。如果你下载最新版本,一切都按预期工作。

1

我已经想出了一个非常hacky的解决方案。如果添加的功能页面:

function format(o, t) { 
    return $.format(o, t); 
} 

您可以表达,然后更改为:

{{= format(new Date(parseInt(comment.DateCreated.substr(6))), 'd') }} 

,它工作正常。这似乎很奇怪,微软创建的两个插件会以这种方式冲突。

0

要格式化的jQuery模板内的日期时间,你可以写一个函数,如:

function formatDate(datetime) { 
    var dateObj = new Date(datetime); 
    var dateStr = (dateObj.getMonth()+1) + "/" + dateObj.getDate() + "/" + dateObj.getFullYear(); 
    return dateStr; // will return mm/dd/yyyy 
} 

然后,您可以从您的jQuery模板中调用这个函数像这样:${formatDate(comment.DateCreated)}

有关详细信息,请参阅: http://api.jquery.com/template-tag-equal

3

这是我用什么

var formatDate = function (datetime) { 
    var dateObj = new Date(parseInt(datetime.replace("/Date(", "").replace(")/", ""), 10)); 
    return dateObj.format("dd-MMM-yyyy"); //01-Jun-2001 
} 

这在我的JQuery模板

$ {formatDate(InceptionDate)}