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'
};
}
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
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>
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With