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

117
Views
JavaScript: is there a way to detect that a given date in such a format is within last X days?

I have a bunch of timestamp formatted like this

const dates = ['2021.6.01', '2021.6.11', '2021.9.02']

I wanted to write a util that can tell me if a date with such a format is within the last X days of another date.

For example, 2021.6.10 is within the last 7 days of 2021.6.12 while 2021.6.01 is not within the last 7 days of 2021.6.12.

I was think the API interface would be but please feel free to suggest a better naming

function isWithinTheLastDays(originalDate, date, days)

I found it really tricky to implement by hand and there are a lot of edge cases.

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

0

Parse the dates with the Date constructor, subtract the two dates and convert the millisecond difference to days (by dividing by 86400000), then check whether it is smaller or equal to days:

function isWithinTheLastDays(originalDate, date, days){
  return (new Date(date) - new Date(originalDate)) / 86400000 <= days;
}

console.log(isWithinTheLastDays('2021.6.10', '2021.6.12', 7)) //2 day diff
console.log(isWithinTheLastDays('2021.6.10', '2021.6.17', 7)) //7 day diff
console.log(isWithinTheLastDays('2021.6.10', '2021.6.18', 7)) //8 day diff

about 4 years ago · Juan Pablo Isaza Report

0

You can try this:

Note: this will return true if the dates is X days after and before the date you've set

const dates = ['2021.08.26', '2021.6.11', '2021.9.02']

function isWithinDays({ originalDate, date, range }) {
  return parseInt(((new Date(date) - new Date(originalDate)) / (1000 * 60 * 60 * 24)), 10) <= range && parseInt(((new Date(date) - new Date(originalDate)) / (1000 * 60 * 60 * 24)), 10) >= 0 ? true : false
}

for (var i = 0; i < dates.length; i++) {
  console.log(isWithinDays({
    originalDate: dates[i],
    date: new Date('2021-08-27'),
    range: 10
  }))
}

about 4 years ago · Juan Pablo Isaza Report

0

turning it to Unix timestamp and subtracting it

function isWithinTheLastDays(originalDate, date, days){
    if(Math.abs(
    new Date(date).getTime()/1000
    - new Date(originalDate).getTime()/1000
    )/60/60/24 >= days){
        return true;
    }else{
        return false;
    };
}
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!