Node.js Date Formats

Here in this theTech52 post, we will see how to use different Node.js date formats. The date formats will be used with the help of a Node.js module. The module is moment.js.

So first we need to install the moment.js module using npm.
$ npm install moment

Next step: When you write code for server, we will use the moment.js module. The code is given below.

var http = require("http");
var moment = require("moment");
var myServer = http.createServer(function(req, res) {
var currentDate = 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:ss");
res.write("<p>Date in D MMM YYYY format: " + date + "</p>");
res.write("<p>Year in YYYY format: " + year + "</p>");
res.write("<p>Current Month is " + month + "</p>");
res.write("<p>Current time is HH:mm:ss " + time + "</p>");

Third Step: Now when you run it on your local host:
$ node server.js

You get the following output in the browser:

Date in D MMM YYYY format: 12 Dec 2015

Year in YYYY format: 2015

Current month is December

Current time is 10:32

That’s it. It is simple to use different date formats using Node.js and moment.js.