I'm nidhin
I'm nidhin

Reputation: 2662

How to format date in meteor template

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

Upvotes: 32

Views: 18526

Answers (3)

user5699596
user5699596

Reputation: 95

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");
        }
    },

    })

Upvotes: 6

Sawant
Sawant

Reputation: 4536

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.

Upvotes: 2

David Weldon
David Weldon

Reputation: 64312

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.

Upvotes: 73

Related Questions