📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Moment.js
Setting up Moment.js
1. Include moment.js in Script tag
<script src="https://MomentJS.com/downloads/moment.js"></script>
<!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
npm install moment
var moment = require('moment');
var a = moment().toString();
console.log(a);
C:\javascript\momentjs-demo>node test.js
Wed Jul 24 2019 17:12:22 GMT+0530
Get today's date using moment.js
const moment = require('moment');
let now = moment();
console.log(now.format());
const moment = require('moment');
let now = moment();
console.log(now.format());
Different ways to create date and time Moment.js objects
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'));
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
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"));
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
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}`);
C:\javascript\momentjs-demo>node date-difference.js
Difference in days: 4
Difference in hours: 96
Moment.js date-time arithmetic
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')}`);
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
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);
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
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());
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
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}.`);
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
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");
}
C:\javascript\momentjs-demo>node validaty.js
day1 is valid
day2 is not valid
Moment.js - 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')}`);
}
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
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");
}
C:\javascript\momentjs-demo>node test.js
The day is within the date range
Moment.js parsing date and time
const moment = require('moment');
let day = "24/07/2019";
let parsed = moment(day, "DD/MM/YYYY");
console.log(parsed.format('ll'));
C:\javascript\momentjs-demo>node test.js
Jul 24, 2019
Moment.js localized date and time
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'));
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
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`);
}
}
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
Comments
Post a Comment
Leave Comment