Web Technologies
Introduction

The Moment.js is an JavaScript library that helps you manage dates. Sometimes It is bit difficult to handle date and time.
Moment.js, the impressive JavaScript library for validating, parsing and manipulating dates and times,time zones.
The moment object in Moment.js is mutable.

Moment was designed to work both in the browser and in Node.js. Moment.js is available on cdnjs.com and on jsDelivr.

Moment.js has robust support for internationalization.


Installation
npm install moment --save   # npm
yarn add moment             # Yarn
Install-Package Moment.js   # NuGet
spm install moment --save   # spm
meteor add momentjs:moment  # meteor
bower install moment --save # bower (deprecated)

Get Current Date and Time

const currentdate = moment();


Manipulating Date 

We can achieve this manipulation via the add() and subtract() methods.

#Add Syntax

moment().add(Number, String);
moment().add(Duration);
moment().add(Object);

#Subtract Syntax

moment().subtract(Number, String);
moment().subtract(Duration);
moment().subtract(Object);

#Calculating the Difference Between Dates

const moment = require('moment');
const dateB = moment('1990-07-01');
const dateC = moment('2019-07-19');
console.log('Difference is ', dateB.diff(dateC, 'days'), 'days');
console.log('Difference is ', dateB.diff(dateC, 'months'), 'months');
console.log('Difference is ', dateB.diff(dateC, 'years'), 'years');


Format Dates
moment().format('MMMM DD YYYY, h:mm:ss a'); // July 14 2019, 12:18:13 pm
moment().format('dddd');                    // Sunday
moment().format("MMM DD YY");               // Jul 14 19
moment().format('YYYY [escaped] YYYY');     // 2019 escaped 2019
moment().format();                         // 2019-07-14T12:22:46+05:30

Date Comparison Methods

Comparison methods are isBefore(), isAfter(), and isSame(). These methods return boolean values that are indicating if one date is before, after, or equal to another date.

const moment = require('moment');
console.log(moment('2019-07-14').isAfter('2019-07-13')); // returns false
console.log(moment('2019-07-14').isAfter('2019-07-20')); // returns true


parseZone

moment.parseZone is equivalent to parsing the string and using moment#utcOffset to parse the zone.


Checking current moment.js locale

This is as simple as calling moment.locale without any parameters.

moment.locale(); // returns 'en'

UTC Offset

This function will return the current offset variation with respect to the system server timezone.

moment().utcOffset(); // (-240, -120, -60, 0, 60, 120, 240, etc.)

Changing locale globally

Moment.js has robust support for internationalization. We easily change the locale as required.

moment.locale('fr');

References

https://momentjs.com/docs/#/use-it/

0