5

I need some help with a javascript code, I need to check two string date values (first date and second date) if the second date is greater than 3 days, I'm getting the values in string format mm/dd/yyyy. Please help.

var firstDate = '10/01/2019'
var secondDate = '10/04/2019'

if ((inputData.firstDate) + 3 === inputData.secondDate) {
  return {
    dateCheck: 'Not greater than 3 days'
  };
} else {
  return {
    dateCheck: 'Greater than 3 days'
  };
}
User863
  • 19,346
  • 2
  • 17
  • 41
AJ152
  • 671
  • 2
  • 12
  • 28
  • 1
    Assuming your dates are written as MM/DD/YYYY you can pass them in to the constructor of the `Date` object and they will be parsed correctly. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Parameters) then you can use the methods on Date to compare. Second, `date + 3 === secondDate` is not really the way to check if something is `>` greater than. There are excellent libraries for dealing with dates like Moment.js https://momentjs.com/ – lemieuxster Jan 26 '19 at 23:41
  • 1
    This question is already answered [here](https://stackoverflow.com/questions/492994/compare-two-dates-with-javascript) – gual Jan 26 '19 at 23:43
  • Can I get an example please. – AJ152 Jan 26 '19 at 23:43

5 Answers5

7

To add N days to a Date you use Date.getDate() + N

var d1 = new Date('10/01/2019');
var d2 = new Date('10/04/2019');
var isGreater = +d2 > d1.setDate(d1.getDate() + 3); // false (equals three days)

Given the above you can make a simple reusable function

/**
 * Check if d2 is greater than d1
 * @param {String|Object} d1 Datestring or Date object
 * @param {String|Object} d2 Datestring or Date object
 * @param {Number} days Optional number of days to add to d1
 */
function isDateGreater (d1, d2, days) {
  d1 = new Date(d1);
  return +new Date(d2) > d1.setDate(d1.getDate() + (days||0))
}

console.log(isDateGreater('10/01/2019', '10/03/2019', 3)); // false (smaller)
console.log(isDateGreater('10/01/2019', '10/04/2019', 3)); // false (equal)
console.log(isDateGreater('10/01/2019', '10/05/2019', 3)); // true (greater than)
// Without the optional third parameter
console.log(isDateGreater('10/01/2019', '10/05/2019')); // true (is greater date)

To recap: make a function that, after adding N days to a date, evaluates two timestamps.

Date.setDate MDN
Date.getDate MDN

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
1

I have enclosed it inside a function so you can test.

Here we are checking if ((date1 - date2) < 259200000) (3 Days in Unix timestamp)

function isItGreaterThan(date1, date2, days) {
  var firstDate = new Date(date1);
  var secondDate = new Date(date2);
  var time = days * 60 * 60 * 24 * 1000
  if ((secondDate.getTime() - firstDate.getTime()) < time) {
    console.log({dateCheck: `Not greater than ${days} days`});
  } else {
    console.log({dateCheck: `Greater than ${days} days`});
  }
}

isItGreaterThan('10/01/2019', '10/02/2019', 3);
isItGreaterThan('10/01/2019', '10/03/2019', 3);
isItGreaterThan('10/01/2019', '10/04/2019', 3);

isItGreaterThan('10/01/2019', '10/02/2019', 10);
isItGreaterThan('10/01/2019', '10/03/2019', 10);
isItGreaterThan('10/01/2019', '10/14/2019', 10);
Web Nexus
  • 1,150
  • 9
  • 28
1

For so many different Date usage I recommend using dateFns. DateFns is date object JS library having many different available methods for date manipulation. Reference : DateFns

You can also format dates in different format using format from library

For this I recommend addDays method from dateFns

const secondDate = '04/04/2019',
firstDate = '04/01/2019'

alert(new Date(secondDate) >= dateFns.addDays(new Date(firstDate), 3))
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js"></script>
Satyam Pathak
  • 6,612
  • 3
  • 25
  • 52
0

Perhaps you could define a helper function to parse your input date strings so that you can perform the comparison between each date with the 3-day offset applied like so:

var firstDate = '10/01/2019'
var secondDate = '10/04/2019'

/*
Define helper function to parse input date string and
return the date as milliseconds since epoch time, whihch
gives us an easy format to compare offset dates
*/
function parseDate(str) {
  
  /*
  Break input string into date parts
  */
  const parts = str.split('/').map(p => parseInt(p));
  
  /*
  Create date object and populate parts
  */
  const date = new Date();
  date.setTime(0);
  date.setDate(parts[0]);
  date.setMonth(parts[1] - 1);
  date.setFullYear(parts[2]);

  /*
  Return date in milliseconds
  */
  return date.getTime()
}

/*
If first input date + 3 days (in milliseconds) is less than second input
date, then second date is not greater than 3 days since first date
*/
if (parseDate(firstDate) + (86400000 * 3) < parseDate(secondDate)) {
  console.log('Not greater than 3 days');
} else {
  console.log('Greater than 3 days');
}
Cid
  • 14,968
  • 4
  • 30
  • 45
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
  • @Cid - yes `parseDate()` rather than `parseData()`. I seem to be hardwired to write data by default. Thanks for spotting that :-) – Dacre Denny Jan 26 '19 at 23:55
0

Subtracts 3 days from second date and checks to see if still greater than first date.

var firstDate = '10/01/2019';
var secondDate = '10/04/2019';
var thirdDate =  '11/01/2019'; // this is to test.

const pastThreeDays = (firstDate, secondDate) => {
  // Time is measured in milliseconds, so lets create a variable for a day.
  const day = 1000 * 60 * 60 * 24;
  let fDate = new Date(firstDate);
  let sDate = new Date(secondDate);
  sDate = new Date(sDate.getTime() - (3 * day));
  console.log(`${fDate} - ${sDate}`);
  // If sDate is still greater than fDate after subtracting 3 days then we are past three days.
  return fDate.getDate() < sDate.getDate();
};

console.log(pastThreeDays(firstDate, secondDate));
console.log(pastThreeDays(firstDate, thirdDate));
Bibberty
  • 4,670
  • 2
  • 8
  • 23