In this recipe, we will look at how we can format our dates and times for display. There are a number of options to accomplish this, such as using Node's util.format()
function but we will use a popular date processing library called moment.js.
In this example, we will demonstrate ways to use moment.js to format dates:
Load the moment.js library:
moment = require 'moment'
For the sake of our examples, create an object literal to represent a date value:
date = year: 2014, month: 11, day: 15, hour: 15
Format dates as strings by using the
format()
function.The
format()
function takes a string containing several formatting tokens.For example, if we use the string
YYYY-MM-DD HH:mm
:# date as 2014-12-15 15:00 console.log moment(date).format('YYYY-MM-DD HH:mm')
The following will be displayed:
2014-12-15 15:00
Likewise, let's use the string
dddd, MMMM...