Open In App

Moment.js moment().max(Moment|String|Number|Date|Array) Method

The moment().max() method limits the moment to a maximum of another moment value. We can also say that m1.max(m2) is the same as m1 = moment.min(m1, m2). This method is the counterpart of moment.min() method.

Syntax:



moment().max(Moment|String|Number|Date|Array);

Parameters: This method can accept the following parameters as mentioned above and described below:

Return Value: This method returns the Moment object calculated after a comparison of the given parameters.



Note:

Moment.js can be installed using the following command:

Installation of moment module:

npm install moment

The below examples will demonstrate the Moment.js moment().max() Method.

Example 1: In this example, we are comparing current moment with the moment 15 days before the current date.




const moment = require('moment');
  
let momentOne = moment();
let momentTwo = moment().subtract(15, 'days');
  
console.log(
`The two Moments are:
    ${momentOne}
    ${momentTwo}
`);
  
let finalMoment =
    momentOne.max(momentTwo);
console.log(
    "The calculated Moments from the above is:",
    finalMoment.toString()
)

Output:

The two Moments are:
    Mon Aug 29 2022 13:27:39 GMT+0530
    Sun Aug 14 2022 13:27:39 GMT+0530
The calculated Moments from the above is: 
    Sun Aug 14 2022 13:27:39 GMT+0530

Example 2: In this example, we are comparing dates, this method will return the minimum of both the dates.




const moment = require('moment');
  
let momentOne = moment(new Date("01-01-2001"));
let momentTwo = moment(new Date("02-02-2002"));
  
console.log(
`The two Moments are:
    ${momentOne}
    ${momentTwo}
`);
  
let finalMoment =
    momentOne.max(momentTwo);
console.log(
    "The calculated Moments from the above is:",
    finalMoment.toString()
)

Output:

The two Moments are:
    Mon Jan 01 2001 00:00:00 GMT+0530
    Sat Feb 02 2002 00:00:00 GMT+0530
The calculated Moments from the above is: 
    Mon Jan 01 2001 00:00:00 GMT+0530

Example 3: In this example, we are comparing the array of moments.




const moment = require('moment');
  
let momentOne = moment();
let momentTwo = moment().subtract(15, 'days');
let momentThree = moment().add(15, 'days');
  
console.log(
`The three Moments are:
    ${momentOne}
    ${momentTwo}
    ${momentThree}
`);
  
let finalMoment =
    momentOne.max(momentTwo , momentThree);
console.log(
    "The calculated Moment from the above is:",
    finalMoment.toString()
)

Output:

The three Moments are:
    Mon Aug 29 2022 13:30:50 GMT+0530
    Sun Aug 14 2022 13:30:50 GMT+0530
    Tue Sep 13 2022 13:30:50 GMT+0530
The calculated Moment from the above is: 
    Sun Aug 14 2022 13:30:50 GMT+0530

Reference: https://momentjs.com/docs/#/manipulating/max/


Article Tags :