Using this function, I'm getting a 7 days difference; how can I test whether a date is before the current date?
function validateDate() { pickedDate = Date.parse("05-Jul-2012".replace(/-/g, " ")); todaysDate = new Date(); todaysDate.setHours(0, 0, 0, 0); dateDifference = Math.abs(Number(todaysDate) - pickedDate); //7 Days=604800000ms if (dateDifference > 604800000) { return false; } else { return true; } }
To check if a date is before another date, compare the Date objects, e.g. date1 < date2 . If the comparison returns true , then the first date is before the second, otherwise the first date is equal to or comes after the second.
Approach 1: Get the input date from user (var inpDate) and the today's date by new Date(). Now, use . setHours() method on both dates by passing parameters of all zeroes. All zeroes are passed to make all hour, min, sec and millisec to 0.
To check if a date is today's date:Use the toDateString() method to compare the two dates. If the method returns 2 equal strings, the date is today's date.
You can directly compare both dates as
return pickedDate <= todaysDate
For exact date comparison considering milliseconds you can use getTime() method
You can parse date as you have done:
pickedDatestr = "09-Apr-2010" var pickedDate = new Date(Date.parse(pickedDatestr.replace(/-/g, " ")))
For date comparison (without time):
function isDateBeforeToday(date) { return new Date(date.toDateString()) < new Date(new Date().toDateString()); } isDateBeforeToday(new Date(2016, 11, 16));
Test cases:
// yesterday isDateBeforeToday(new Date(2018, 12, 20)); // => true // today isDateBeforeToday(new Date(2018, 12, 21)); // => false // tomorrow isDateBeforeToday(new Date(2018, 12, 22)); // => false
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