Moment JS Check if Date is Past or not Example

By Hardik Savani January 6, 2021 Category : jQuery

Here, i will show you moment check date is past. i would like to share with you how to check date is past in moment. We will look at example of jquery moment check date is past. i would like to share with you moment.js check if date is past.

Here, i will give you simple example of jquery moment js check given date is past or not using diff() and isBefore() method provide you last next month date.

let's see both example with output:

Example 1:

<!DOCTYPE html>

<html>

<head>

<title>jquery moment example - ItSolutionStuff.com</title>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" crossorigin="anonymous"></script>

</head>

<body>

<h1>jquery moment example - ItSolutionStuff.com</h1>

</body>

<script type="text/javascript">

var todayDate = moment('02-01-2021', 'DD-MM-YYYY');

var pastDate = moment('01-01-2021', 'DD-MM-YYYY');

var dDiff = todayDate.diff(pastDate);

if (dDiff > 0) {

console.log('Date is not past');

}else{

console.log('Date is past');

}

var dDiff2 = pastDate.diff(todayDate);

if (dDiff2 > 0) {

console.log('Date is not past');

}else{

console.log('Date is past');

}

</script>

</html>

Output:

Date is not past

Date is past

Example 2:

<!DOCTYPE html>

<html>

<head>

<title>jquery moment example - ItSolutionStuff.com</title>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" crossorigin="anonymous"></script>

</head>

<body>

<h1>jquery moment example - ItSolutionStuff.com</h1>

</body>

<script type="text/javascript">

var todayDate = moment('02-01-2021', 'DD-MM-YYYY');

var pastDate = moment('01-01-2021', 'DD-MM-YYYY');

if (todayDate.isBefore(pastDate)) {

console.log('Date is not past');

}else{

console.log('Date is past');

}

</script>

</html>

Output:

Date is past

I hope it can help you...

Tags :
Shares