MDN wants to learn about developers like you:

Learn web development

Date formatting using moment

The default rendering of dates from our models is very ugly: Tue Dec 06 2016 15:49:58 GMT+1100 (AUS Eastern Daylight Time). In this section we'll show how you can update the BookInstance List page from the previous section to present the due_date field in a more friendly format: December 6th, 2016. 

The approach we will use is to create a virtual property in our BookInstance model that returns the formatted date. We'll do the actual formatting using moment, a lightweight JavaScript date library for parsing, validating, manipulating, and formatting dates.

Note: It is possible to use moment to format the strings directly in our Pug templates, or we could format the string in a number of other places. Using a virtual property allows us to get the formatted date in exactly the same way as we get the due_date currently. 

Install moment

Enter the following command in the root of the project:

npm install moment --save

Create the virtual property

  1. Open ./models/bookinstance.js.
  2. At the top of the page, import moment.
    var moment = require('moment');

Add the virtual property due_back_formatted just after the url property.

.get(function () {
  return moment(this.due_back).format('MMMM Do, YYYY');

Note: The format method can display a date using almost any pattern. The syntax for representing different date components can be found in the moment documentation.

Update the view

Open /views/bookinstance_list.pug and replace due_back with due_back_formatted.

      if val.status!='Available'
        //span  (Due: #{val.due_back} )
        span  (Due: #{val.due_back_formatted} )       

That's it. If you go to All book-instances in the sidebar, you should now see all the due dates are far more attractive!


Next steps


Document Tags and Contributors

 Contributors to this page: chrisdavidmills, bunnybooboo
 Last updated by: chrisdavidmills,