How do I format Date/Time with jQuery Templates?

时间秒杀一切 提交于 2019-12-18 19:32:09

问题


i've just started using jQuery Templates as my javascript template engine. My question is, how can i format a date (returned from a ASP.NET Json ActionResult) in the form:

/Date(1288709830000)/

I tried doing the following:

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

Note the above uses the new jquery globalization plugin to add the $.format method. Also note that {{= comment.DateCreated }} is long hand for saying ${comment.DateCreated}.

I'd really appreciate it if you could help.


回答1:


This is what I used

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

And this in my JQuery Template

${formatDate(InceptionDate)}




回答2:


This does actually work. I was using the beta version hosted on the Microsoft CDN. If you download the latest version everything works as expected.




回答3:


I've come up with a very hacky solution. If you add the following function to the page:

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

You can then change the expression to:

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

And it works fine. This seems strange that two plugins both created by Microsoft would conflict in this way.




回答4:


To format a datetime within a jQuery template you could write a function like:

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

You can then call this function from within your jQuery template like so: ${formatDate(comment.DateCreated)}

For more details see: http://api.jquery.com/template-tag-equal



来源:https://stackoverflow.com/questions/4341518/how-do-i-format-date-time-with-jquery-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!