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"
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"
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
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
}