Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate if date is before date of current date

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;     } } 
like image 230
John Avatar asked Jul 05 '12 12:07

John


People also ask

How do you check if a date is before another date?

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.

How do you validate the selected date is a current date or not?

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.

How do I validate a date today?

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.


2 Answers

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, " "))) 
like image 180
Hemant Metalia Avatar answered Sep 22 '22 23:09

Hemant Metalia


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 
like image 23
Christoph Bühler Avatar answered Sep 21 '22 23:09

Christoph Bühler