How to format date in meteor template

I'm nidhin picture I'm nidhin · Feb 28, 2014 · Viewed 18k times · Source

I need to display a date from database in the format 'mm-dd-yyyy'. As its saved in ISO format in mongodb how can I convert it in the template ? Here is my code.

       Template.templatename.vname = function () {      
        return Posts.find(); 
        }

And in template

{{#each vname}}
    {{ date }} 
{{/each}}

Now its getting displayed like Tue Feb 04 2014 00:00:00 GMT+0530 (IST)

I need to show it as mm-dd-yyyy

Answer

David Weldon picture David Weldon · Feb 28, 2014

You may want to create a global helper like:

Template.registerHelper('formatDate', function(date) {
  return moment(date).format('MM-DD-YYYY');
});

Then you can use it like:

{{#each vname}}
  {{formatDate date}}
{{/each}}

This solution depends on moment which is a handy date manipulation library. If you prefer to produce the string without using moment, there are a number of answers for this including this one.