How to Use Moment.js

Saturday, Aug 16, 2014
Tags: JavaScript moment.js

With recent work formatting of dates has been an important feature. From my reading around the bloggersphere I came across a JavaScript library that I have found to be useful - moment.js.

To start using moment.js download the library from http://momentjs.com/.

Create a html page and add a reference to the library.

In the body of the page add content to display a time.

<div>
    <h2>Basic moment.js demonstration</h2>
    <input type="button" value="Get Date" onclick="getDate()" /><br />
    <span id="demoSpan"></span>
</div>

Next in the header add a JavaScript function to get the date from the moment.js library and display it.

<script>
    function getDate() {
        var theDate = moment().format("MM/DD/YYYY hh:mm:ss a");;

        var mySpan = document.getElementById("demoSpan");

        mySpan.innerHTML = "The date is " + theDate;
    }
</script>

Note that initiating a date using moment() returns a timestamp and it can be formatted using the format function.

Putting this altogether creates a web page that

This is a basic introduction to the moment.js library. The library is extensive allowing manipulation, customization, parsing and more. The documentation is comprehensive and can be found at http://momentjs.com/docs/.

You can down load this demo at Github.

Addendum 8/19/2014 Have uploaded a second file to the project that has more moment.js functionality

(C)2014-Today  Coding With An Accent