Book Image

CoffeeScript Application Development Cookbook

By : Mike Hatfield
Book Image

CoffeeScript Application Development Cookbook

By: Mike Hatfield

Overview of this book

Table of Contents (18 chapters)
CoffeeScript Application Development Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Formatting dates with moment.js


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.

Getting ready

We will begin by making sure the moment NPM module is installed:

npm install moment --save

How to do it...

In this example, we will demonstrate ways to use moment.js to format dates:

  1. Load the moment.js library:

    moment = require 'moment'
    
  2. For the sake of our examples, create an object literal to represent a date value:

    date = year: 2014, month: 11, day: 15, hour: 15
    
  3. 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...