Check if user entered date matches current date or future date

I searched the web to find a javascript function that can check if the date entered by the user is the current date or future date, but I did not find a suitable answer, so I did it myself. Satisfaction If this can be achieved with a single line code.

function isfutureDate(value) { var now = new Date; var target = new Date(value); if (target.getFullYear() > now.getFullYear()) { return true; } else if(target.getFullYear() == now.getFullYear()) { if (target.getMonth() > now.getMonth()) { return true; } else if(target.getMonth() == now.getMonth()) { if (target.getDate() >= now.getDate()) { return true; } else { return false } } } else{ return false; } } 
+11
source share
5 answers

You can compare two dates as if they were integers:

 var now = new Date(); if (before < now) { // selected date is in the past } 

Both must be Date.

The first google search results in the following: Check if there is a date in the past Javascript

However, if you like programming, here is a tip:

  • A date formatted as YYYY-MM-DD may be something like 12/28/2013.
  • And if we change the date, then this is 2013-12-28.
  • We remove the colons and we get 20131228.
  • We set a different date: 2013-11-27, which is finally 20131127.
  • We can perform a simple operation: 20131228 - 20131127

Enjoy.

+26
source

here is a version that compares only the date and excludes the time.

Typescript

 const inFuture = (date: Date) => { return date.setHours(0,0,0,0) > new Date().setHours(0,0,0,0) }; 

ES6

 const inFuture = (date) => { return date.setHours(0,0,0,0) > new Date().setHours(0,0,0,0) }; 
+2
source

try this one

 function isFutureDate(idate){ var today = new Date().getTime(), idate = idate.split("/"); idate = new Date(idate[2], idate[1] - 1, idate[0]).getTime(); return (today - idate) < 0 ? true : false; } 

Demo

 console.log(isFutureDate("02/03/2016")); // true console.log(isFutureDate("01/01/2016")); // false 
0
source

ES6 version with an acceptable future option.

I made this little function that allows you to use some space for maneuver (for example, if data comes from a little fast hours).

A Date object and toleranceMillis required, which is a valid number of seconds in the future (default is 0).

 const isDistantFuture = (date, toleranceMillis = 0) => { // number of milliseconds tolerance (ie 60000 == one minute) return date.getTime() > Date.now() + toleranceMillis } 
0
source

try it

 function IsFutureDate(dateVal) { var Currentdate = new Date(); dateVal= dateVal.split("/"); var year = Currentdate.getFullYear(); if (year < dateVal[2]) { return false;//future date } else { return true; //past date } } 
0
source

Source: https://habr.com/ru/post/1501419/


All Articles