Moment.js – A javascript date library

A javascript date library for parsing, validating, manipulating, and formatting dates.

There are multiple ways to refer Moment.js, but the popular way is via Nuget package manager.

To install/refer Moment.js, run the following command in the package manager console in visual studio.

Install-Package Moment.js

Now let me run you through some of the examples using Moment.js library

1. To get the current date and time, just call moment() with no parameters.

var now = moment();

//Tue Oct 01 2013 08:40:23 GMT+0550

2. You can format date by multiple ways. e.g

moment().format('MMMM Do YYYY, h:mm:ss a'); // October 1st 2013, 12:19:57 pm
moment().format('dddd'); // Tuesday
moment().format("MMM Do YY"); //Oct 1st 13
moment().format('YYYY [escaped] YYYY'); //2013 escaped 2013
moment().format(); //2013-10-01T12:20:35+05:30

3. You can validate date e.g

moment("not a real date").isValid(); //false

moment("01/01/2013").isValid(); //true

4. You can get or set hour, minutes, seconds etc.

moment().second(); // Number
moment().minute(); // Number
moment().hour(); // Number

5. You can manipulate dates/months/year by multiple ways. e.g

moment().add('days', 7).subtract('months', 1).year(2009).hours(0).minutes(0).seconds(0)

//Tue Sep 08 2009 00:00:00 GMT+0550

6. You can query moment object, e.g

moment('2010-10-20').isBefore('2010-12-31', 'year'); // false
moment('2010-10-20').isBefore('2011-01-01', 'year'); // true
moment().isLeapYear(); //false
moment().isDST(); //Daylight saving time - false

Moment.js documentation can be found here.

jsFiddle example


2 thoughts on “Moment.js – A javascript date library

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s