问题
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