-1

I'm completely new to Javascript and need to produce a simple boolean that determines:

IF "January 01 2018" is within 1-7 days of "January 03 2018" "true","false"

Kelly
  • 1
  • You can use the moment library. See https://stackoverflow.com/questions/16424702/count-days-until-today-moment-js and https://momentjs.com/docs/ – Odyssee Jul 25 '18 at 14:51
  • Does within mean only before or before and after? What if they are the same date (0 days apart)? – James Jul 25 '18 at 14:51
  • 2
    Welcome, you can have a look at [this question](https://stackoverflow.com/q/542938/4636715) for computing the difference between two dates. Then apply your conditional logic on the result. – vahdet Jul 25 '18 at 14:51
  • Possible duplicate of [Compare two dates with JavaScript](https://stackoverflow.com/questions/492994/compare-two-dates-with-javascript) – Nima Jul 25 '18 at 14:55

2 Answers2

0

Simple answer is (if by within you mean before or after x days):

var days = 7; // number of days
var delta = days * 24 * 60 * 60 * 1000; // in milliseconds
var result = Math.abs(new Date("January 03 2018") - new Date("January 01 2018")) < delta; // true
onestep.ua
  • 118
  • 7
0

This code should do it. a and b are both Date objects that are being compared. Credit to Ulysse BN for shortening the code.

function compareDates (a, b, difference) {
    if (difference == undefined) {
        difference = 1000*60*60*24*7; // if difference is not specified set it to 7 days
    }
    return Math.abs(a.getTime() - b.getTime()) < difference; // if the absolute difference is less than specified return true
}
Aplet123
  • 33,825
  • 1
  • 29
  • 55