【问题标题】:Format date in Meteor Handlebars bracers {{ timestamp }}在 Meteor Handlebars 括号 {{ timestamp }} 中格式化日期
【发布时间】:2013-07-26 07:12:11
【问题描述】:

在使用 Meteor's Handlebar 护腕时,如何将 {{ timestamp }} 的输出从 Thu Jul 25 2013 19:33:19 GMT-0400 (Eastern Daylight Time) 转换为 Jul 25

试过{{ timestamp.toString('yyyy-MM-dd') }},但报错

【问题讨论】:

标签: javascript jquery node.js meteor handlebars.js


【解决方案1】:

使用车把助手:

Template.registerHelper("prettifyDate", function(timestamp) {
    return new Date(timestamp).toString('yyyy-MM-dd')
});

然后在你的html中:

{{prettifyDate timestamp}}

如果你使用时刻:

Template.registerHelper("prettifyDate", function(timestamp) {
    return moment(new Date(timestamp)).fromNow();
});

【讨论】:

  • 正如上面提到的@JonathanLonowski,值得注意的是timestamp.toString() 将忽略传递给它的任何参数。我发现使用 MomentJS 让这一切变得异常简单。
  • @Akshat,注意经过一些翻转后,现在的语法是Template.registerHelper
【解决方案2】:

这对我有用

Handlebars.registerHelper("prettifyDate", function(timestamp) {
     return (new Date(timestamp)).format("yyyy-MM-dd");
});

【讨论】:

    【解决方案3】:

    这对我有用。

    toString("yyyy-MM-dd") - 不转换它。

    Template.registerHelper("prettifyDate", function(timestamp) {
        var curr_date = timestamp.getDate();
        var curr_month = timestamp.getMonth();
        curr_month++;
        var curr_year = timestamp.getFullYear();
        result = curr_date + ". " + curr_month + ". " + curr_year;
        return result;
    });
    

    【讨论】:

      【解决方案4】:

      使用车把助手:

      const exphbsConfig = exphbs.create({
          defaultLayout: 'main',
          extname: '.hbs',
          helpers:{
      
              prettifyDate:  function(timestamp) {
                  function addZero(i) {
                      if (i < 10) {
                        i = "0" + i;
                      }
                      return i;
                  }
      
                  var curr_date = timestamp.getDate();
                  var curr_month = timestamp.getMonth();
                  curr_month++;
                  var curr_year = timestamp.getFullYear();
      
                  var curr_hour = timestamp.getHours();
                  var curr_minutes = timestamp.getMinutes();
                  var curr_seconds = timestamp.getSeconds();
      
                  result = addZero(curr_date)+ "/" + addZero(curr_month) + "/" + addZero(curr_year)+ '   ' +addZero(curr_hour)+':'+addZero(curr_minutes)+':'+addZero(curr_seconds);
                  return result;
              }
      
          }    
      
      });
      
      app.engine('hbs', exphbsConfig.engine);
      app.set('view engine', '.hbs');
      

      然后在你的 html 中:

        <div class="card-footer">
            <small class="text-muted">Atualizada em: {{prettifyDate updatedAt}}    </small>
          </div>
      

      【讨论】:

        猜你喜欢
        • 2013-09-05
        • 2014-10-08
        • 1970-01-01
        • 2023-03-19
        • 2015-07-16
        • 1970-01-01
        • 1970-01-01
        • 2017-09-19
        • 2019-01-29
        相关资源
        最近更新 更多