Nyxynyx
Nyxynyx

Reputation: 63619

Format date in Meteor Handlebars bracers {{ timestamp }}

When using Meteor's Handlebar bracers, how do you convert the output of {{ timestamp }} from Thu Jul 25 2013 19:33:19 GMT-0400 (Eastern Daylight Time) to Jul 25?

Tried {{ timestamp.toString('yyyy-MM-dd') }} but it gave an error

Upvotes: 11

Views: 19132

Answers (4)

Anderson Lima
Anderson Lima

Reputation: 11

Use a handlebars helper:

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');

Then in your html:

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

Upvotes: 0

mdujava
mdujava

Reputation: 327

This works for me.

toString("yyyy-MM-dd") - doesn't convert it.

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

Upvotes: 3

Tarang
Tarang

Reputation: 75945

Use a handlebars helper:

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

Then in your html:

{{prettifyDate timestamp}}

If you use moment:

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

Upvotes: 41

Harry
Harry

Reputation: 4773

This worked for me

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

Upvotes: 1

Related Questions