32

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

I'm nidhin
  • 2,592
  • 6
  • 36
  • 62

3 Answers3

73

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.

Community
  • 1
  • 1
David Weldon
  • 63,632
  • 11
  • 148
  • 146
  • 4
    If you want to set a custom format for the date in each template like I did, you can do something like this `Template.registerHelper('timeFormat', function(date, format) { return moment(date).format(format); });` and then in the template: `{{timeFormat datetime "MM.DD / H:mm"}}` – Kris Haamer May 10 '16 at 22:08
6

moment is a greet lib

meteor add momentjs:moment

use moment in helper

Template.home.helpers({
    momentFormate: function(time) {

        if ((moment().unix() - moment(time).unix()) < 3600) {
            return moment(time).fromNow();
        } else {
            return moment(time).format("YYYY-MM-DD HH:mm");
        }
    },

    })
user5699596
  • 95
  • 1
  • 5
2

Here is a solution that works in Meteor without any dependency on another package:

// global helper
Template.registerHelper('formatDate', function(date) {
    return monthNames[date.getMonth()] + " " + date.getDate() + ", " + date.getFullYear();
});

This will return a date string formatted as "December 11, 2015". Move around getMonth(), getDate() and getFullYear() for your preferred format. For more formatting options, check out other methods of Date object.

Sawant
  • 4,321
  • 1
  • 27
  • 30