27 Aug 2013

Format a Date with Moment.js and node.js

Format dates and times using the Moment.js module and node.js.

Install the Moment.js module using npm:

$ npm install moment

server.js:

var http = require("http");
var moment = require("moment");

var server = http.createServer(function(req, res) {

  var now = moment(new Date());

  var date = now.format("D MMM YYYY");
  var year = now.format("YYYY");
  var month = now.format("MMMM");
  var time = now.format("HH:mm");

  res.write("<p>Today's date is " + date + "</p>");
  res.write("<p>The year is " + year + "</p>");
  res.write("<p>The month is " + month + "</p>");
  res.write("<p>The time is " + time + "</p>");

  res.end();

}).listen(8080);

Start:

$ node server.js

Now test in your browser:

http://localhost:8080

Today's date is 27 Aug 2013

The year is 2013

The month is August

The time is 09:29