Format dates

353 words, 2-minute read

Date values, such as a ${ data.date } expression, returns a native JavaScript date as a string which isn’t particularly readable:

This post was written on Thu Jan 23 2025 00:00:00 GMT+0000 (Coordinated Universal Time).

It’s better show the date in a friendlier format and allow the site to be localised for different countries and languages.

Update the formatting library #

We’re going to reuse the lib/format.js function library. If you’ve not already done so, import the tacs object at the top of the file so functions can access any global property:

lib/format.js

// formatting functions
import { tacs } from 'publican';

// ...

Add the following functions if not already defined:

lib/format.js

// default language
function lang(locale) {
  return locale || tacs?.config?.language || 'en-US';
}

// create a date
function cDate(d) {
  d = new Date(d);
  return +d && !isNaN(d) && d instanceof Date ? d : new Date();
}

// friendly date format
export function dateHuman(d, locale) {

  return new Intl.DateTimeFormat(lang(locale), { dateStyle: 'long' })
    .format( cDate(d) );

}

The library has already been imported into the publican.config.js configuration file and appended to the tacs.fn.format object so no additional code is required.

Use in content and templates #

A function named tacs.fn.format.dateHuman() is now available to content and templates which can output formatted dates in any language, e.g.

<!-- en-US default -->
<p><em>This post was written on
${ tacs.fn.format.dateHuman( data.date ) }.</em></p>

<!-- Spanish alternative -->
<p><em>Esta publicación fue escrita el
${ tacs.fn.format.dateHuman( data.date, 'es-ES' ) }.</em></p>

The result:

This post was written on January 23, 2025.

Esta publicación fue escrita el 23 de enero de 2025.