Home > Software design >  I have to Compare two time string in nodejs using moment
I have to Compare two time string in nodejs using moment

Time:08-31

here is my code I am comparing two time strings using isBefore function but I am getting an error isBefore is not a function. What's wrong here?

let currentTime = moment().format("HH:MM");
let endTime = moment(_et).format("H:MM");
let available = currentTime.isBefore(endTime) ? "Y" : "N"
console.log("Is Available",available);

CodePudding user response:

It's because isBefore is only available on a moment object when you call .format method you get a string representation of the date not a moment object

let _et = '2022-12-01 11:22';
let currentTime = moment();
let endTime = moment(_et);
let available = currentTime.isBefore(endTime) ? "Y" : "N"
console.log("Is Available", available);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

If your _et variable contain just time you can compare it by creating moment object and format you can use h:mma

let _et = '07:22';
let currentTime = moment('06:22', 'h:mma');
let endTime = moment(_et, 'h:mma');
let available = currentTime.isBefore(endTime) ? "Y" : "N"
console.log("Is Available", available);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

CodePudding user response:

The error is that when you use format you are transforming the date into string and a string has no function isBefore, in order to use isBefore you can use do it like this:

let currentTime = moment();
let endTime = moment(_et);
let available = currentTime.isBefore(endTime) ? "Y" : "N"
console.log("Is Available",available);

The format function is only to format the string that you want to show.

CodePudding user response:

When you call format method on any moment it returns string. So, You should use something like this:

let currentTime = moment();
let endTime = moment(_et);
let available = currentTime.isBefore(endTime) ? "Y" : "N"
console.log("Is Available",available);
  • Related