如何使用jQuery模板格式化日期/时间?

我刚开始使用jQuery模板作为我的javascript模板引擎。 我的问题是,我如何格式化日期(从ASP.NET Json ActionResult返回)格式:

/Date(1288709830000)/ 

我尝试过以下操作:

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

注意上面使用新的jquery全球化插件来添加$.format方法。 另请注意, {{= comment.DateCreated }}可以说${comment.DateCreated}

如果你能提供帮助,我真的很感激。

这是我用过的

 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)}

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

我想出了一个非常讨厌的解决方案。 如果您将以下function添加到页面:

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

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

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

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

要在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