Skip to content

Instantly share code, notes, and snippets.

@sdaityari
Forked from kawadhiya21/momentjs.md
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sdaityari/09663a9c9c307189353c to your computer and use it in GitHub Desktop.
Save sdaityari/09663a9c9c307189353c to your computer and use it in GitHub Desktop.

Displaying date and time in JavaScript has never been an issue but manipulating them has never been an easy task. Earlier, programmers manually made date/time realted calculations but with time, analytics became important, with demand for more complex calculations. To match up those modern requirements, we have Moment.js.

All the code required in this tutorial runs with the core JavaScript file from Moment.js. Download it from the links on the home page and save it as moment.js in the root folder.

Introduction

As the tagline says "Parse, validate, manipulate, and display dates in JavaScript", Moment.js has definitely eased up the task of performing these actions. It makes calculations easier and displays them in a range of formats. A small step to get started would be to start with the docs.

Beginning with Moment.js

There are no great requirements for this library, you simply need to include moment.js as shown in the docs in the index.html.

<html>
<head>
    <title>
        Moment JS
    </title>
    <script src="moment.js"></script>
</head>
<body>
    
</body>
</html>

We are going to use JavaScript based alert and console.log() to see the results. We write our first basic function to get current time and date.

<script type="text/javascript">
    function basic () {
        alert(moment());
    }
    basic();
</script>

This will give you an output like the following — Thu Jul 17 2014 23:29:36 GMT+0530.

Also, you can put in a custom time in various other standard ISO-8601 formats listed here. Let us try 2013-02-08 09 as an argument in moment().

function advanced () {
    alert(moment("2013-02-08 09"));
}
advanced();

Hitting this on the browser will give you Fri Feb 08 2013 09:00:00 GMT+0530. Changing formats is that easy! Other ISO-8601 formats may also be used.

However, these formats are seldom used when the inputs come from a user. Users may enter the date in informal ways and it can become different to process each user. Moment.js has the capability to deal with this as well.

Identifying Non Standard Formats

It has String + Format options where the date can be parsed easily with options. Let us look at some of the examples to understand this.

function non(){
    alert(moment("07-17-2014", "MM-DD-YYYY"));
    }
non();

This gives the result Thu Jul 17 2014 00:00:00 GMT+0530. Let us interchange the month and date along with changing the format to DD-MM-YYYY.

function non(){
    alert(moment("17-07-2014", "DD-MM-YYYY"));
    }
non();

The result turns out to be same. This feature gives more flexibility to the developer to introduce user specific date formats. Also Moment.js accepts all kinds of separators. For example, dates like 07/17/2014 are treated in the same way as 07-17-2014.

Identifying Multiple Formats

If there is unsurity in the format entered by user, multiple formats can be specified as well.

function multiple(){
    alert(moment("24-07-2014", ["MM-DD-YYYY", "DD-MM", "DD-MM-YYYY"]));
}
multiple();

In this example, Moment.js selects the last format and the result is Thu Jul 24 2014 00:00:00 GMT+0530. But, if an ambiguity occurs, Moment.js chooses the intiial one.

Validation

How do you validate a certain Moment.js object? You can simply check it using moment().isValid() which returns a boolean value.

Setting Present Time

Many a times it happens that a user enters a particular date or month and then it has to be converted to full Date() object manually. Well MomentJS has a function for this which assumes other parameters to be default if you specify one of them. Example:

  1. moment() - Gives current date and time.
  2. moment("10","hh") - Will assign the hour as 10. The smaller unit are assigned 0 and elder units are taken from current time. Hence this will make minute and seconds as 0 but month and year will retain the original value ie Fri Jul 18 2014 10:00:00 GMT+0530. Month and date might be different when you execute it on your system but hour, minute and seconds will reflect these values.
  3. moment("3","MM") - This time we set the month instead. Hence date becomes 1st March and rest 0 ie Sat Mar 01 2014 00:00:00 GMT+0530.
  4. Mutliple parameter can also be specified.
  5. moment({hour: 5, minute: 10, seconds: 20}) - Shows Sat Jul 19 2014 05:10:20 GMT+0530 as output.
  6. moment("Mar 3 05:13:07", "MMM DD hh:mm:ss") - Shows Mon Mar 03 2014 05:13:07 GMT+0530.

Copying Moment Object

It is rather easy to copy momentjs object. See the docs here.

var a = moment([2012]);
var b = moment(a);
a.year(2000);
b.year(); // 2012

Getting the parameters

Suppose a moment object is created and now various elements like days, months, year etc are to be deduced from the object. Moment.js provides simple API to it.

var a = moment("2013-02-08 09");
a.second();
a.minute();
a.day(); // gives '5' as output. Week index (0-6)
a.month(); // gives '1' as output. Month index(0-11)
a.year(); // gives '2013'
a.week(); // gives '6' (ie 6th week of the year)

More related to these methods can be found here.

Some Queries

Simple queries like comparing dates and leap years can be performed on moment objects too.

moment('2010-10-20').isBefore('2010-10-21'); //true
moment('2010-10-20').isAfter('2010-10-21'); //false
moment([2000]).isLeapYear(); //true

These are really useful operations which a web developer needs on daily basis.

Conclusion

With many more such functionalities Moment.js has enormous potential that one should explore. I hope after reading this, Moment.js interests you and you can spend more time in exploring the same using the docs.

There are tons of more functions and combinations of which can almost make a time machine. I will therefore leave you here and proceed on to another interesting topic. All the code used in this tutorial can be found on Github.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment