Date-handling in jQuery is so much easier with moment.js.
In the last tip, I showed you the fundamentals of moment.js, and I hope that got you started. This tip will show you some more basics and hopefully increase your interest in the moment.js plugin.
Moment.get ()
Sometimes you need to be able to do something at a specific time. In my first example, I show you a way to do that using the “set” function that moment.js provides. My example defines a simple clock that updates every 1 second, and I want to something different every 15 seconds, in this case change the background color in a <div> box.
In a real-world example, you might want to rotate through different figures or something of the sort.
Here is the code to define the clock:
$('#clock').html(moment().format('HH:mm:ss') );
I then use setInterval to call updateClock every 1 second.
setInterval(updateClock, 1000);
Here is the function that sets the clock and uses moment.get() to get the second part of the current time.
var currentSeconds = moment().get('second');
I then use a simple if/else block to set the color:
if ( currentSeconds == 15 ) {
$('#setColor').css('background-color','BurlyWood');
}
else if ( currentSeconds == 30 ) {
$('#setColor').css('background-color','SeaGreen');
}
else if ( currentSeconds == 45 ) {
$('#setColor').css('background-color','Wheat');
}
else if ( currentSeconds == 00 ) {
$('#setColor').css('background-color','Crimson');
}
The HTML to define the clock and the box looks like this:
<div id="clock" class="h1">...</div>
<div id="setColor" style="width:100px;height:100px;background-color:Tomato" class="border border-dark p2 text-center"></div>
Figure 1 shows the results (Note: I used Bootstrap together with jQuery to easily make the figures in this article.):
Figure 1: Use moment.get() to change color every 15 seconds. (Click image or here to try the example.)
There is also a moment.set() function that can change the date, but I simply could not get my head around a good example, so I left it out, but it’s there and can be called if ever needed.
You can of course also use moment.js to get the year, month, week, day, and likewise from a date, which is very useful when you want to make something happen on any specific part of any date.
Use moment.js to Add to or Subtract from a Date
Another useful function is the ability to add to or subtract from a date in an easy way. This is handy when you create from/to date fields when creating lists to display a subset of data.
You will most likely have a date picker to select a date range, but wouldn’t it be nice if you could provide the date range that the user is mostly likely to select when executing the list? Moment.js lets you do that easily, as you can see by the examples below.
Set the root date:
$('#root-date').html( moment().format('DD-MM-YYYY HH:mm:ss') );
Add to the root date:
$('#ex1').html( moment().add(70,'days').format('DD-MM-YYYY HH:mm:ss') + ' - add 70 days' );
$('#ex2').html( moment().add(5,'hours').format('DD-MM-YYYY HH:mm:ss') + ' - add 5 hours' );
$('#ex3').html( moment().add(5,'minutes').add(2,'months').format('DD-MM-YYYY HH:mm:ss') + ' - add 2 months and 3 minutes' );
$('#ex4').html( moment().add(2,'isoweek').format('DD-MM-YYYY HH:mm:ss') + ' - add 2 iso weeks' );
Subtract from the root date:
$('#ex5').html( moment().subtract(2,'isoweek').format('DD-MM-YYYY HH:mm:ss') + ' - subtract 2 iso weeks' );
$('#ex6').html( moment().subtract(70,'days').subtract(5,'hours').subtract(100,'seconds').format('DD-MM-YYYY HH:mm:ss') + ' - subtract 70 days, 5 hours and 100 seconds' );
Figure 2 shows the results:
Figure 2: Add to or subtract from a date. (Click image or here to try the example.)
Use moment.js to Calculate Time Between Dates
The last example shows how you can calculate the hours, minutes, and seconds between two dates using moment.js.
Let’s start by looking at the result, shown in Figure 3:
Figure 3: Calculate the time between dates. (Click image or here to try the example.)
The main thing in this example is the function called calculateDuration(), which looks like this:
function calculateDuration()
{
A)
// Get dates
var fromDate = $('#from-date').val();
var toDate = $('#to-date').val();
B)
var fromDate = moment(fromDate,'DD-MM-YYYY HH:mm:ss');
var toDate = moment(toDate,'DD-MM-YYYY HH:mm:ss');
C)
var seconds = toDate.diff(fromDate,'seconds');
D)
if ( seconds > 0 ) {
$('#duration-date-seconds').html( seconds );
var time = moment.duration(seconds,'seconds').format('HH:mm:ss');
$('#duration-date-time').html( time );
} else {
$('#duration-date-seconds').html( 'error' );
$('#duration-date-time').html( 'error' );
}
}
Here’s what happens:
The function retrieves the from and to dates from the input fields at A).
The two dates are then converted to moment.js objects in B).
At C), the seconds between the two dates are calculated using the diff() method.
When the seconds are calculated, we convert back to hours, minutes, and seconds unless the seconds were less than zero, which means that the from date was bigger than the to date, in which case we show an error.
All this happens at D).
I have made it so that you can change the dates and calculate the time.
Let’s Sum It Up
I have shown you some basic examples of what moment.js can do, and I hope these will get you started.
Moment.js has much more than what I have written about, so if you need things like locales or validation or if you want to dig deeper into the “display” options, look here:
Display
https://momentjs.com/docs/#/displaying/
Query (validation)
https://momentjs.com/docs/#/query/
Locale
https://momentjs.com/docs/#/durations/locale/
Till next time, dig into the world of moment.js and become a true date master. Discover and use all the good functionality that has been put into moment.js.
LATEST COMMENTS
MC Press Online