Search code examples
jqueryasp.net-mvc-3jquery-templates

How do I display date field in jQuery template?


I'm trying to learn ASP.NET MVC3 & jQuery, and I'm banging my head with the jQuery template feature.

I have a template with a date field. If I assign the date value just by typing down the date field (ie. ${dateField}), what's getting displayed is something along the lines of /Date(338583832901), which I don't want, of course...

I just couldn't find a way to display the date value itself (some formatting will be a welcome bonus, of course...). If found the following question: How do I format Date/Time with jQuery Templates? which discusses the same issue, but the answers refer to an old version of the globalization plug in, and the suggested solution won't work with the new one (globalize.js).

So, how can I display date value with jQuery template?

Thanks!


Solution

  • If you don't want to use the globalization plugin you could write a format function yourself and format the date however you want. For example:

    function format(date) {
        var date = new Date(parseInt(date.substr(6)));
        return date.getDate() + '/' + 
               (date.getMonth() + 1) + '/' + // notice that getMonth() returns 0 based months
               date.getFullYear();
    }
    

    and now in your template simply call it:

    {{= format(SomeDateProperty) }}