Home > Software design >  Comparing date and time with moment js
Comparing date and time with moment js

Time:04-14

In my react app I am receiving an endDate, and also separately receiving an endTime. I have to check if that endDate and endTime are before the current date and time.

let endDate = "04/13/2022"; 
let endTime = "22:00"
console.log(moment(endDate, "MM/DD/YYYY", endTime).isBefore(moment());
//true

Today's date is the same as the endDate but the time is earlier than the endTime so I should see False instead of true. The times are not being compared. Does anyone know how to resolve this?

CodePudding user response:

Combine the date and time strings, and parse as one full date-time string.

const endDate = '04/13/2022'; 
const endTime = '22:00';

const date = moment(`${endDate} ${endTime}`, 'MM/DD/YYYY HH:mm');

console.log(date.isBefore(moment())); // false
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.2/moment.min.js"></script>

  • Related