formatting an ISO date field in an #each in the template

1,829 views
Skip to first unread message

Ken Yee

unread,
Feb 21, 2013, 5:31:19 PM2/21/13
to meteo...@googlegroups.com
Thought this would be something simple, but it looks like the mustache library which handlebars is based on doesn't support this yet?
  https://github.com/mustache/spec/issues/41

How do you folks do this?
e.g., display a list of documents in a collection along w/ the last modified timestamp of each.
In the MongoDB collection, the date is an ISO date stored as the value Date.now().

Workaround seems to be to store the date in string format and then put that value in the {{#each}} loop, but this would have internationalization issues.
I did find the meteor-moment library for formatting, but it looks like I'd have to register a Handlebars helper for something that should be built-in :-P

 thanks,

ken

erundook

unread,
Feb 22, 2013, 4:59:37 AM2/22/13
to meteo...@googlegroups.com
Hey Ken,

You can use something like this:
Handlebars.registerHelper 'isoDate', (date) ->
  if date then new Date(date).toISOString()

пятница, 22 февраля 2013 г., 2:31:19 UTC+4 пользователь Ken Yee написал:

Ken Yee

unread,
Feb 24, 2013, 4:34:56 PM2/24/13
to meteo...@googlegroups.com
Thanks erundook.
I was actually trying to format the ISO date that Meteor/mongodb stored, not convert a Javascript date object into

I guess the question is whether Meteor should just be bundling vanilla Handlebars or whether it should include helpers to make Handlebars more usable (being able to format a date for display on the web client seems to be one of those things that really should be included to make people's lives easier :-)

Anyways, what I did was add this to a file in the client subfolder (it can also be added to the isClient part of the toplevel app if you want to put everything into a single giant JS file like the examples):
  //  format an ISO date using Moment.js
  //  http://momentjs.com/
  //  moment syntax example: moment(Date("2011-07-18T15:50:52")).format("MMMM YYYY")
  //  usage: {{dateFormat creation_date format="MMMM YYYY"}}
  Handlebars.registerHelper('dateFormat', function(context, block) {
    if (window.moment) {
      var f = block.hash.format || "MMM DD, YYYY hh:mm:ss A";
      return moment(context).format(f); //had to remove Date(context)
    }else{
      return context;   //  moment plugin not available. return data as is.
    };
  });

Then for display of my collection HTML, I used this in the template:
  {{dateFormat gallerymodified format="MMM d YYYY"}}

 ken
Reply all
Reply to author
Forward
0 new messages