Cody CMS
Fork me on GitHub

Date formatting

Q: How do I format dates in my ejs view?

A1: the Context object contains a few formatting functions

<%= formatDate( aDateObject ) %>  -> Localized  DD-MM-YYYY
<%= formatTime( aDateObject ) %>  -> HH:MM:SS
<%= formatShortTime( aDateObject ) %>  ->  HH:MM 

A2: if these are not enough, I would advise using moment.js.

 

Q: How do I use moment.js?

A: Install it in the Context and setup the language to the language of the current page

  • install the package:
    npm install moment --save
  • put it in the current context, do this in your controller's constuctor (or doRequest)
    this.context.moment = require("moment"); 
    this.context.moment.lang(this.context.page.language);
  • in your ejs file use all the moment.js functions
    <%= moment( new Date() ).format() %>
    <%= moment().startOf('day').fromNow() %>