Javascript Web Development

A Moment.js In Time

June 27th, 2018 | By Jscrambler | 6 min read

Moment.js is a free and open-source JavaScript library that removes the need to use the native JavaScript Date object directly. The library is a wrapper for the Date object (in the same way that jQuery is a wrapper for JavaScript), extending functionality and making objects more accessible for ease of use.

Moment.js was designed to work both in the browser and in Node.js.

Vanilla JavaScript’s Date object can be unwieldy and is not as convenient as using a framework like Moment.js. If you want to do complex parsing, validation, and manipulation of dates, you’ll end up writing a lot of code.

Moment.js extends the native JavaScript date capabilities with different features, such as relative time, calendar time, durations, and multi-language support. It also has a decent list of plugins that allow additional features like local time-zone support, recurrence, and even Twitter integration.

Parsing and Formatting in Moment.js

You can edit time in hours, minutes, and days based on specific or relative times and dates. Perhaps you need to display a countdown timer for the launch of your new indie game or for when your mixtape drops in the next year.

Examples of how to use Moment.js

  • Displaying basic and formatted date outputs

  • Displaying relative time

  • Displaying locale time (US, UK, GMT, etc.)

  • Adding and subtracting dates

Moment.js funcionalities

Moment.js has a flexible parser that allows for a range of functionality. If you know the format of an input string, you can use that to parse it. For instance, a specific date will be called:

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


The above strings would correspond to the Moment.js shorthand as shown below:

Key

Shorthand

years

y

quarters

Q

months

M

weeks

w

days

d

hours

h

minutes

m

seconds

s

milliseconds

ms

moment().format('MMMM Do YYYY, h:mm:ss a'); // May 05th 2018, 7:20:58 pm
moment().format('dddd');                    // Thursday
moment().format("MMM Do YY");               // May 24th 18
moment().format('YYYY [escaped] YYYY');     // 2018 escaped 2018
moment().format();                          //2018-05-12T14:03:38-07:00


The Moment prototype is exposed through the moment() function. If you want to integrate your functions, this is where you would add them.

To get the current date and time, call javascript moment() with no parameters, like this:

var now = moment();


This is essentially the same as calling moment(new Date()). Unless you specify a time zone offset, parsing a string will create a date in the current time zone.

moment("2010-10-20 4:30", "YYYY-MM-DD HH:mm");   // parsed as 4:30 local time


Instead of modifying the native Date.prototype, Moment.js creates a wrapper for the Date object. To get this wrapper object, simply call moment() with one of the supported input types.

Moment.js lets you format your desired time in almost any pattern through its method of chaining. This allows you to do crazy things like the following:

moment().add(7, 'days').subtract(2, 'months').year(2009).hours(3).minutes(6).seconds(9);[javascript]


Relative Time

moment("20111031", "YYYYMMDD").fromNow(); // 7 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 6 years ago
moment().startOf('day').fromNow();        // 14 hours ago
moment().endOf('day').fromNow();          // in 10 hours
moment().startOf('hour').fromNow();       // 4 minutes ago


Calendar Time

moment().subtract(10, 'days').calendar(); // 05/14/2018
moment().subtract(6, 'days').calendar();  // Last Friday at 2:03 PM
moment().subtract(3, 'days').calendar();  // Last Monday at 2:03 PM
moment().subtract(1, 'days').calendar();  // Yesterday at 2:03 PM
moment().calendar();                      // Today at 2:03 PM
moment().add(1, 'days').calendar();       // Tomorrow at 2:03 PM
moment().add(3, 'days').calendar();       // Sunday at 2:03 PM
moment().add(10, 'days').calendar();      // Fri, May 25, 2018 10:47 AM


Note: Moments are mutable. Calling any of the manipulation methods will change the original moment. If you want to create a copy and manipulate it, you should use moment#clone before manipulating the moment. See the Pen Basic Moment.js examples by TotalPro (@TotalProfessional) on CodePen.

If you want to create a copy and manipulate it, you should use moment#clone before manipulating the moment.

Hacking time itself...

According to cybersecurity experts, every 39 seconds, a system is hacked. They calculated this based on data to come up with this highly accurate statistical estimate in 2007.

With these scary stats in mind, we'll build a timer that displays how often there is a security breach to remind you why it's so important to protect your code. Timer number one will surprise you!

Moment.js: Building a timer

To get started, install Moment.js with NPM or reference the CDN as in the following Codepen.io example.

The moment is available on cdnjs.com and on jsDelivr.com. You can also install it through Yarn or NPM, with instructions for how to do so on momentjs.com.

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

var now = moment();
moment();
// From 2.14.0 onward, the formatting below is also supported
moment([]);
moment({});


Moment.js abstracts many of the pains of dealing with time manipulation in JavaScript. It also extends functionality by allowing for various plugins, such as the one used in our timer, countdown.js

Create moment:

//Call the moment to display Time
$(".now").text(moment(now).format('h:mm:ss a'));
$(".then").text(moment(then).format('h:mm:ss a'));
$(".duration").text(moment(now).to(then));


Use countdown.js (the moment.js plugin used for counting down) to countdown the time between hacks and display images and messages when timer Jquery makes development painless with its handy methods.

var now = moment(); // new Date().getTime();
var then = moment().add(39, 'seconds'); // new Date(now + 60 * 1000);

$(".now").text(moment(now).format('h:mm:ss a'));
$(".then").text(moment(then).format('h:mm:ss a'));
$(".duration").text(moment(now).to(then));

(function timerLoop() {
  $(".difference").text(moment().to(then));
  $(".countdown").text(countdown(then).toString();
  requestAnimationFrame(timerLoop);
})();


There are essentially only three-time elements in our timer:

  1. The now

  2. The then div

  3. The difference in time.

We then create a loop that calculates the difference between “.then” and “.now” to continually display the difference in time as a countdown.

Another important time-saving piece of our timer functionality is provided by the javascript window.requestAnimationFrame() which animates our countdown loop efficiently with a single function.

The window.requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. The method takes a callback as an argument to be invoked before the repaint. You can thank Paul Irish for this extremely useful function.

If we were to skip both jQuery and requestAnimationFrame we’d have our work cut out for us, and we’d go from 10 lines of code to significantly more. As with programming and most things in life, you can shortcut everything.

Our completed timer app should look like this:

See the Pen Is your system secure? by TotalPro (@TotalProfessional) on CodePen.

Time-manipulating powers: conclusion

Learning how to harness the time-manipulating powers of moment.js and countdown.js is easy enough. The real lesson is that taking advantage of any APIs available can make your development life easier.

An alternative option for time manipulation in JavaScript would be date-fns which provides extensive options with a small footprint. Unlike Moment.js, it uses pure functions and returns a new date instance rather than changing the passed one.

Whatever your choice is, dealing with time is a common development hurdle that is simplified with the use of these frameworks. Moment.js requires few dependencies and is small by most standards. If you need to manipulate, parse, or validate time in your next project and don’t want to reinvent the wheel, look no further.

Jscrambler

The leader in client-side Web security. With Jscrambler, JavaScript applications become self-defensive and capable of detecting and blocking client-side attacks like Magecart.

View All Articles

Must read next

Web Development

Creating a Real-Time Location Tracking App with NativeScript-Vue

In this blog post, we explore the NativeScript-Vue template for building a real-time location tracking app that uses the Google Maps API.

March 19, 2020 | By Wern Ancheta | 11 min read

Web Development

How to Build Real-time Applications Using Node.js and RethinkDB

The RethinkDB is awesome NoSQL! This database can provide a fully support for realtime applications just using changefeed + socket.io.

August 4, 2016 | By Jscrambler | 5 min read

Section Divider

Subscribe to Our Newsletter