June 27, 2018

A Moment.js In Time

by Jscrambler

A Moment.js In Time

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 was designed to work both in the browser and in Node.js.

Vanilla JavaScript’s Date object can be unwieldy and is just 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 a variety of features, such as relative time, calendar time, durations and multi-language support. It also has a decent list of plugins that allow for 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, days based on specific or relative time 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. Here are a few 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 has a flexible parser that allows for a huge range of functionality. If you know the format of an input string, you can use that to parse a moment. For instance, a specific date will be called with:

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 own functions, this is where you would add them.

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

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 their method 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: It should be noted that 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!

To get started, install Moment.js with NPM or reference the CDN as in the following Codepen.io example.
Moment is available on cdnjs.com and on jsDelivr.com. You can also install 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 when 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” display image and message when timer jquery makes the development painless with it's 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 3 time elements in our timer, the now the then div and the difference in time. We then create a loop which 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 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, shortcut everything.

Our completed timer app should look like this:

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

Learning how to harness the time manipulating powers of moment.js and countdown.js is easy enough. The real lesson is in taking advantage of any API’s available can make your development life easier. An alternative option for time manipulation in JavaScript would be date-fns which provides extensive options in 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 diminutive 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.