Home > Blockchain >  String dates comparison in javascript
String dates comparison in javascript

Time:10-16

So, I have two variables and one function:

 function addDays(date, days) {
    var result = new Date(date);
    result.setDate(result.getDate()   days);
    return result;
  }
  
 const dateToCompare=moment.utc(endDate).format('DD-MM-YYYY')
 const maximum=moment.utc(addDays(new Date(),14)).format('DD-MM-YYYY')
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

However, I do not know how to compare them, since they are now formatted as strings, but at the same time new Date(dateToCompare) doesn't work.

Can someone give me a hint?

CodePudding user response:

If what you're trying to do is strip out the time and just compare the dates, don't do a string conversion; just set the hour, minutes, and seconds on your Date objects to zero before making your date comparison.

let foo = new Date();
console.log(foo);// date includes time
foo.setHours(0); foo.setMinutes(0); foo.setSeconds(0);
console.log(foo) // date set to midnight (in your timezone)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Why are you using built–in methods to add days when you are using moment.js? Consider:

let maximum = moment.utc().add('day',14).format('DD-MM-YYYY')

To set a date to the start of a day, use the moment.js startOf method:

let maximum = moment.utc().add('day',14).startOf('day')
let dateToCompare = moment.utc(endDate).startOf('day')

You can compare the dates as strings if formatted as YYYY-MM-DD, or just leave them as moment objects and compare those using isSame, isAfter, isSameOrBefore, etc.

When parsing strings as in:

const dateToCompare=moment.utc(endDate)

you should always pass the format to parse unless endDate is a Date or moment object. new Date(dateToCompare) doesn't work because Why does Date.parse give incorrect results?

  • Related