Published on

Define Handlebars Helper to Format Date

Authors

It is fairly common when rendering dates to want to output them in a certain String format. This is luckily fairly easy to achieve with a handlebars helper.

First, let's install moment.js to help more easily parse dates and format them using a date string:

yarn add moment

Then define the helper as follows:

const hb = require('handlebars')
const moment = require('moment')
//...

hb.registerHelper('dateFormat', function (date, options) {
  const formatToUse =
    (arguments[1] && arguments[1].hash && arguments[1].hash.format) || 'DD/MM/YYYY'
  return moment(date).format(formatToUse)
})

In the above:

  • we call the helper dateFormat
  • the format is optional
    • this is achieved using the && then || expression above. This would be easier if JS had the elvis operator which would express the above as: arguments[1]?.hash?.format ?: "DD/MM/YYYY"
  • We then use moment to initialize using the provided date and parse it using the date format

This can now be used in your templates as follows:

{{dateFormat some.dateVariable format='MMMM'}}

Or leaving off format:

{{dateFormat some.dateVariable}}

As a bonus if you need a helper to get the current date (let's call it dateNow) it would be defined as:

hb.registerHelper('dateNow', () => {
  return new Date()
})

This is used as simply as:

{
  {
    dateNow
  }
}

And can be combined with our previous helper as follows:

{{dateFormat (dateNow) format='MMMM'}}