How to format date in meteor template

不问归期 提交于 2019-11-26 15:45:57

问题


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


回答1:


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.




回答2:


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

    })



回答3:


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.



来源:https://stackoverflow.com/questions/22087907/how-to-format-date-in-meteor-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!