Zend certified PHP/Magento developer

Managing Dates and Times Using Moment.js

Working with dates and times has always been a bit cumbersome. I’ve always thought that a JavaScript library for manipulating dates would be quite helpful. It was only recently that I was introduced to Moment.js, the awesome JavaScript library for validating, parsing, and manipulating dates and times.

Getting Started with Moment.js

Moment.js is freely available for download from the project’s home page. Moment.js can be run from the browser as well as from within a Node.js application. In order to use it with Node, install the module using the following command.

[code]
npm install moment
[/code]

Then, simply require() and use it in your application as shown below.

[js]
var moment = require(‘moment’);

moment().format();
[/js]

In order to run Moment from the browser, download the script and include it using a script tag, as shown in the following example. Moment.js creates a global moment object which can be used to access all the date and time parsing and manipulation functionality.

[html]


[/html]

Date Formatting

In the past, I recall converting date strings into Date objects, grabbing individual pieces of data, and then performing string concatentations. Moment.js has simplified the process of date conversion to any particular format. Date format conversion with Moment is simple, as shown in the following example.

[js]
moment().format(‘YYYY MM DD’);
[/js]

moment() gives the current date and time, while format() converts the current date and time to the specified format. This example formats a date as a four digit year, followed by a space, followed by a two digit month, another space, and a two digit date. You can see this code in action by checking out this demo.

Date Validation

Another annoying task that Moment.js has simplified is date validation. In order to perform validation, simply pass a date string to the moment object and call the isValid() method. This method returns true if the date is valid, and false otherwise. An example of this is shown below, along with this accompanying demo.

[js]
var dateEntered = $(‘#txtEnteredDate’).val();

if (!moment(dateEntered,’MM-DD-YYYY’).isValid()) {
console.log(‘Invalid Date’);
} else {
console.log(‘Valid Date’);
}
[/js]

There are a number of other helpful flags in the object returned by moment():

  • overflow – This is set when an overflow occurs. An example would be the 13th month or 32nd day.
  • invalidMonth – Set when the month is invalid, like Jannnuaarry.
  • empty – Set when the entered date contains nothing parsable.
  • nullInput – Set when the entered date is null.

Manipulating Dates

There are a number of options for manipulating the moment object. For example, you can add or subtract days, months, years, etc. This is achieved via the add() and subtract() methods. The following example shows how seven days, months, or weeks are added to the current date.

[js]
moment().add(‘days’, 7); // adds 7 days to current date
moment().add(‘months’, 7); // adds 7 months to current date
moment().add(‘years’, 7); // adds 7 years to current date
[/js]

Similarly, the subtract() method is shown below.

[js]
moment().subtract(‘days’, 7); // subtracts 7 days to current date
moment().subtract(‘months’, 7); // subtracts 7 months to current date
moment().subtract(‘years’, 7); // subtracts 7 years to current date
[/js]

Time From Now

Another common task is determining how much time exists between two dates. For calculating time from the current date, Moment.js uses a method named fromNow(). Here is a sample which checks how much time exists from the current time:

[js]
moment().fromNow();
[/js]

This code sample displays “a few seconds ago.” If we supply a date to the moment object it would display the time range from now as per the difference. For example, the following code displays “7 days ago.”

The post Managing Dates and Times Using Moment.js appeared first on SitePoint.