Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

167
Views
String dates comparison in javascript

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')

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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?

about 4 years ago · Juan Pablo Isaza Report

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!