【问题标题】:How to format date in meteor template如何在流星模板中格式化日期
【发布时间】:2014-04-01 00:38:54
【问题描述】:

我需要以“mm-dd-yyyy”格式显示数据库中的日期。由于它以 ISO 格式保存在 mongodb 中,我如何在模板中转换它? 这是我的代码。

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

在模板中

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

现在它像Tue Feb 04 2014 00:00:00 GMT+0530 (IST)一样显示

我需要显示为mm-dd-yyyy

【问题讨论】:

    标签: meteor handlebars.js


    【解决方案1】:

    时刻是一个问候库

    meteor add momentjs:moment
    

    在助手中使用时刻

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

    【讨论】:

      【解决方案2】:

      这是一个在 Meteor 中工作的解决方案,不依赖于其他包:

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

      这将返回格式为“2015 年 12 月 11 日”的日期字符串。移动getMonth()getDate()getFullYear() 以获得您的首选格式。有关更多格式选项,请查看Date 对象的其他方法。

      【讨论】:

        【解决方案3】:

        您可能想要创建一个全局帮助器,例如:

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

        然后你可以像这样使用它:

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

        这个解决方案依赖于moment,这是一个方便的日期操作库。如果您更喜欢在不使用矩的情况下生成字符串,有很多答案,包括this one

        【讨论】:

        • 如果你想像我一样为每个模板中的日期设置自定义格式,你可以这样做Template.registerHelper('timeFormat', function(date, format) { return moment(date).format(format); });,然后在模板中:{{timeFormat datetime "MM.DD / H:mm"}}
        猜你喜欢
        • 1970-01-01
        • 2016-03-23
        • 1970-01-01
        • 2016-12-09
        • 1970-01-01
        • 1970-01-01
        • 2012-05-17
        • 2013-09-05
        • 1970-01-01
        相关资源
        最近更新 更多