Last Updated: February 25, 2016
·
9.228K
· kaptainzero

A very short introduction to Moment.js

Do you like getting neat dates in your javascript application / website? in the easiest way.. then you have to take a look @ moment.js.

Moment.js is the best date formatting library I've ever met in the world of javascript, you can use it in Node and in browser alike.

To you it in Node.js you've to install it first, using npm:

npm install moment

then in your app:

var moment = require('moment');

In browser, you'll include it like any other javascript lib:

<script src="moment.js"></script>

It's also available on many public CDNs..

you're ready to use moment.js now :))

you can do it as simple as:

var now = moment(); // this will get the current date & time.
var day = moment("Jul 18, 2013"); // accepting string date.

ISO-8601 formats are supported, for more info visit http://momentjs.com/docs/#/parsing/string/

you can validate date strings easly:

moment("not_a_date").isValid(); // this will return false

if you know the format of the input date string you can use it to parse a moment, noting that the parse will ignore non-alphanumeric characters, so the following are the same:

moment("12-25-1995", "MM-DD-YYYY");
moment("12\25\1995", "MM-DD-YYYY");

moment also accepts Unix time format:

var day = moment.unix(1318781876.721);

Moment accepts date in many other formats, check the main site for more information

One of the good features of moment.js is the 'fromNow()' function

moment([2007, 0, 29]).fromNow(); // 4 years ago
moment([2007, 0, 29]).fromNow(true); // 4 years

This is not everything in moment.js so please refer to the site: http://momentjs.com/ for more :)