check whether the date entered by the user is current date or the future date

前端 未结 5 540
离开以前
离开以前 2020-12-18 19:50

I was browsing through the net to find a javascript function which can check whether the date entered by the user is current date or the future date but i didn\'t found a s

相关标签:
5条回答
  • 2020-12-18 20:02

    here's a version that only compares 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)
    };
    
    0 讨论(0)
  • 2020-12-18 20:05

    try this

    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 讨论(0)
  • 2020-12-18 20:14

    try out this

    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 讨论(0)
  • 2020-12-18 20:15

    ES6 version with tolerable future option.

    I made this little function that allows for some wiggle room (incase data coming in is from a slightly fast clock for example).

    It takes a Date object and toleranceMillis which is the number of seconds into the future that is acceptable (defaults to 0).

    const isDistantFuture = (date, toleranceMillis = 0) => {
        // number of milliseconds tolerance (i.e. 60000 == one minute)
        return date.getTime() > Date.now() + toleranceMillis
    }
    
    0 讨论(0)
  • 2020-12-18 20:16

    You can compare two dates as if they were Integers:

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

    Just both of them must be Date.

    First search in google leads to this: Check if date is in the past Javascript

    However, if you love programming, here's a tip:

    1. A date formatted like YYYY-MM-DD could be something like 28-12-2013.
    2. And if we reverse the date, it is 2013-12-28.
    3. We remove the colons, and we get 20131228.
    4. We set an other date: 2013-11-27 which finally is 20131127.
    5. We can perform a simple operation: 20131228 - 20131127

    Enjoy.

    0 讨论(0)
提交回复
热议问题