Moment JS Tutorial

The moment js tutorial shows how to work with date and time in JavaScript with moment.js module.

Moment.js

The moment.js is a lightweight JavaScript date library for parsing, validating, manipulating, and formatting dates.
Read more at the official documentation https://momentjs.com/

Setting up Moment.js

Different ways we can set up the moment.js for your project.

1. Include moment.js in Script tag

We can directly include moment.js inside the script tag and start working with MomentJS.
<script src="https://MomentJS.com/downloads/moment.js"></script> 
For example:
<!DOCTYPE html>
<html>
<head>
    <title>Moment JS Tutorial</title>
    <script src="https://MomentJS.com/downloads/moment.js"></script>
    
</head>
<body>
 <div style = "font-size:25px" id = "todaysdate"></div>
</body>

 <script type="text/javascript">
  let now = moment();
  let time = now.format();
  console.log(now.format());
  document.getElementById("todaysdate").innerHTML = time;
    </script>
</html>

2. Using Node.js

If you are opting for this method, make sure you have Node.js and npm installed on your system. You can use the following command to install MomentJS −
npm install moment
Create a JavaScript file named "test.js" and add the following code to it:
var moment = require('moment');
var a = moment().toString();
console.log(a);
Now, in the command prompt, run the command node test.js as shown in the below output −
C:\javascript\momentjs-demo>node test.js
Wed Jul 24 2019 17:12:22 GMT+0530
We are using node js to demonstrates these tutorial examples.

Get today's date using moment.js

The example prints today's date and time.
const moment = require('moment');
let now = moment();
console.log(now.format());
Let's understand the above example.
We load the Moment.js library:
const moment = require('moment');
We get the current local DateTime object with moment():
let now = moment();
We format the output with format(). By default, we get a long date-time format:
console.log(now.format());

Different ways to create date and time Moment.js objects

We can use several ways to create date and time Moment.js objects. These objects have to be formatted later to human-readable format.
Example: create a JavaScript file named "create-objects.js" file and add the following code to it:
const moment = require('moment');

let d1 = moment("2019-07-24");
console.log(d1.format('ll'));

let d2 = moment([2019, 06, 24]);
console.log(d2.format('ll'));

let d3 = moment({ year :2019, month :06, day :24, 
hour :15, minute :10, second :3, millisecond :123});
console.log(d3.format('ll'));

let d4 = moment(1563967658917);
console.log(d4.format('ll'));

let d5 = moment(new Date(2019, 06, 24));
console.log(d5.format('ll'));
Run above JavaScript code with the following command:
C:\javascript\momentjs-demo>node create-objects.js
Jul 24, 2019
Jul 24, 2019
Jul 24, 2019
Jul 24, 2019
Jul 24, 2019

Moment.js formatting date-time

Moment.js objects are formatted with the format() function. There are also options for localized formats.
Example: create a JavaScript file named "format.js" file and add the following code to it:
const moment = require('moment');

let now = moment();

console.log("ISO")
console.log(now.format());

console.log("\nTime")
console.log(now.format("HH:mm:ss"));
console.log(now.format("h:mm:ss a"));

console.log("\nDate")
console.log(now.format("dddd, MMMM Do YYYY"));
console.log(now.format("YYYY-MM-DD"));

console.log("\nLocalized")
console.log(now.format("LT"));
console.log(now.format("LTS"));
console.log(now.format("LTS"));
console.log(now.format("L"));
console.log(now.format("l"));
Run above JavaScript code with the following command:
C:\javascript\momentjs-demo>node format.js
ISO
2019-07-24T17:21:56+05:30

Time
17:21:56
5:21:56 pm

Date
Wednesday, July 24th 2019
2019-07-24

Localized
5:21 PM
5:21:56 PM
5:21:56 PM
07/24/2019
7/24/2019

Moment.js calculating date-time difference

With the diff() function, we can calculate the difference between two date-time objects.
Example: create a JavaScript file named "date-difference.js" file and add the following code to it:
const moment = require('moment');

let d1 = moment('2019-07-20');
let d2 = moment('2019-07-24');

let days = d2.diff(d1, 'days');
console.log(`Difference in days: ${days}`);

let hours = d2.diff(d1, 'hours');
console.log(`Difference in hours: ${hours}`);
Run above JavaScript code with the following command:
C:\javascript\momentjs-demo>node date-difference.js
Difference in days: 4
Difference in hours: 96

Moment.js date-time arithmetic

The add() function is used to add date and time to the moment object and the subtract() function subtract date and time from the moment object.
Example: create a JavaScript file named "add-sub.js" file and add the following code to it:
const moment = require('moment');

let now = moment();

console.log(`Now: ${now.format('ll')}`);

now.add('4', 'days');
console.log(`Adding four days: ${now.format('ll')}`);

now.subtract('3', 'years');
console.log(`Subtracting 3 years: ${now.format('ll')}`);
Run above JavaScript code with the following command:
C:\javascript\momentjs-demo>node add-sub.js
Now: Jul 24, 2019
Adding four days: Jul 28, 2019
Subtracting 3 years: Jul 28, 2016

Moment.js date-time parts

In the following example, we get the parts of the current date-time.
Example: create a JavaScript file named "parts.js" file and add the following code to it:
const moment = require('moment');

let now = moment();

let year = now.get('year');
let month = now.get('month');  // 0 to 11
let date = now.get('date');
let hour = now.get('hour');
let minute = now.get('minute');
let second = now.get('second');
let millisecond = now.get('millisecond');

console.log("Year: " + year);
console.log("Month: " + month);
console.log("Date: " + date);
console.log("Hour: " + hour);
console.log("Minute: " + minute);
console.log("Second: " + second);
console.log("Millisecond: " + millisecond);
Run above JavaScript code with the following command:
C:\javascript\momentjs-demo>node parts.js
Year: 2019
Month: 6
Date: 24
Hour: 17
Minute: 28
Second: 47
Millisecond: 879

Moment.js day of the week, month, year

The following example calculates the day of the week, month, and year.
Example: create a JavaScript file named "dayof.js" file and add the following code to it:
const moment = require('moment');

let now = moment();

console.log("Day of week: " + now.weekday()); 
console.log("Day of month: " + now.date()); 
console.log("Day of year: " + now.dayOfYear()); 
Run above JavaScript code with the following command:
C:\javascript\momentjs-demo>node weeks_quarter.js
Week of year: 30
Quarter of year: 3
Weeks in year: 52

Moment.js relative date-time

We can compute relative date-time with fromNow(), startOf(), and endOf() functions.
Example: create a JavaScript file named "relative_time.js" file and add the following code to it:
const moment = require('moment');

let day = moment().startOf('year');
let now = moment();

let days = now.diff(day, 'days');

console.log(`${days} have passed since the start of the year.`);

let val = moment().endOf('day');
let mins = val.diff(now, 'minutes');

console.log(`The day will end in ${mins} minutes.`);

let day2 = moment("2028-12-20")
let diff = day2.fromNow();

console.log(`The day will come ${diff}.`);
Run above JavaScript code with the following command:
C:\javascript\momentjs-demo>node relative_time.js
204 have passed since the start of the year.
The day will end in 379 minutes.
The day will come in 9 years.

Moment.js - date validation example

We can use the isValid() method to check if the date and time object is valid.
Example: create a JavaScript file named "validity.js" file and add the following code to it:
const moment = require('moment');

let day1 = moment('2019-07-23');
let day2 = moment('2019-07-34');

if (day1.isValid()) {

    console.log("day1 is valid");
} else {
    
    console.log("day1 is not valid");
}

if (day2.isValid()) {

    console.log("day2 is valid");
} else {
    
    console.log("day2 is not valid");
}
Run above JavaScript code with the following command:
C:\javascript\momentjs-demo>node validaty.js
day1 is valid
day2 is not valid

Moment.js - isBefore() and isAfter() functions

The isBefore() and isAfter() functions can be used to determine if a date is before or after another date. In the example, we compare three dates using isBefore() and isAfter() functions.
const moment = require('moment');

let d1 = moment("2019-07-19");
let d2 = moment("2019-07-20");
let d3 = moment("2019-07-22");

if (d1.isAfter(d2)) {

    console.log(`${d1.format('ll')} is after ${d2.format('ll')}`);
} else {

    console.log(`${d1.format('ll')} is before ${d2.format('ll')}`);
}

if (d2.isBefore(d3)) {

    console.log(`${d2.format('ll')} is before ${d3.format('ll')}`);
} else {

    console.log(`${d2.format('ll')} is after ${d3.format('ll')}`);
}
Run above JavaScript code with the following command:
C:\javascript\momentjs-demo>node test.js
Jul 19, 2019 is before Jul 20, 2019
Jul 20, 2019 is before Jul 22, 2019

The moment.js - isBetween() function

The isBetween() function checks if a date is in the given date range.
const moment = require('moment');

let d1 = moment("2019-07-20");

if (d1.isBetween('2019-07-19', '2019-07-24')) {
    console.log("The day is within the date range");
}
Run above JavaScript code with the following command:
C:\javascript\momentjs-demo>node test.js
The day is within the date range

Moment.js parsing date and time

We can parse a string representation of date and time by passing the date and time format to the moment() function.
const moment = require('moment');

let day = "24/07/2019";
let parsed = moment(day, "DD/MM/YYYY");

console.log(parsed.format('ll'));
Run above JavaScript code with the following command:
C:\javascript\momentjs-demo>node test.js
Jul 24, 2019

Moment.js localized date and time

With the locale() function, we can set the locale in which we get the output.
const moment = require('moment');

moment.locale('sk');
let now = moment();
console.log(now.format('LLLL'));

moment.locale('de');
now = moment();
console.log(now.format('LLLL'));

moment.locale('hu');
now = moment();
console.log(now.format('LLLL'));
Run above JavaScript code with the following command:
C:\javascript\momentjs-demo>node test.js
streda 24. júl 2019 17:52
Mittwoch, 24. Juli 2019 17:52
2019. július 24., szerda 17:52

Moment.js leap year

A leap year is a year containing an additional day. The reason for an extra day in the calendar is the difference between the astronomical and the calendar year.
const moment = require('moment');

// Assume year >= 1582 in the Gregorian calendar.

let years = [ 2000, 2002, 2004, 2008, 2012, 2016, 2020,
    1900, 1800, 1600 ];

for (year of years) {

    let ym = moment([year]);

    if (ym.isLeapYear()) {

        console.log(`${year} is a leap year`);
    } else {
        
        console.log(`${year} is not a leap year`);
    }
}
Run above JavaScript code with the following command:
C:\javascript\momentjs-demo>node test.js
2000 is a leap year
2002 is not a leap year
2004 is a leap year
2008 is a leap year
2012 is a leap year
2016 is a leap year
2020 is a leap year
1900 is not a leap year
1800 is not a leap year
1600 is a leap year

Reference

Comments