日期格式化和比较Javascript

时间:2016-08-20 07:45:55

标签: javascript jquery date

这里我想对输入的当前日期进行比较。

<script type="text/javascript">
    $(document).ready(function(){
        $("#date").change(function(){
            var realDate = new Date();
            var startDate = new Date($('#date').val());
            if (realDate >= startDate) {
                $('#infobros').removeClass('hidden');
            }else{
                $('#infobros').addClass('hidden');
            }
        });
    });
function validateForm(){
    var realDate = new Date();
    var startDate = new Date($('#date').val());

    if (realDate >= startDate){
      alert('Please Change your date Start');
      $('#date').focus();
      return false;
    }
  } 
</script>

在那里我想让我的身份#infobors删除课程hidden当我将startDate输入低于我的realDatestartDate相同时或者超过realDate

但是,现在如果我输入相同的日期到当前日期#infobros仍在执行。

btw:我的格式为startDate = YYYY-MM-DD

但我不知道我的真实日期的格式

我希望有人可以帮助我,让我的脚本正常工作..

btw:这是我的格式realDate:

photo

有人可以帮我改为:YYYY-MM-DD

3 个答案:

答案 0 :(得分:0)

这是我写的dateUtility函数。我知道它有漏洞,因为它被其他代码包围但它给了你很多你需要的东西。它甚至照顾了闰年和5种国际日期模式!

function setDateComponents(regularExpressionResultsArray){
    if ( this.dateUtilDatePattern == "M/d/yyyy" || this.dateUtilDatePattern == "MM/dd/yyyy" ) {
        this.month = parseInt( eliminateLeadingZero(regularExpressionResultsArray[ 1 ]) ) -1;
        this.day =  parseInt( eliminateLeadingZero(regularExpressionResultsArray[ 2 ]) );
        this.year = parseInt( regularExpressionResultsArray[ 3 ] );
        return;
    }

    if ( this.dateUtilDatePattern == "d/M/yyyy" || this.dateUtilDatePattern == "dd/MM/yyyy" ) {
        this.day = parseInt( eliminateLeadingZero(regularExpressionResultsArray[ 1 ]) );
        this.month =  parseInt( eliminateLeadingZero(regularExpressionResultsArray[ 2 ]) ) - 1;
        this.year = parseInt( regularExpressionResultsArray[ 3 ] );
        return;
    }

    if ( this.dateUtilDatePattern == "d.M.yyyy" || this.dateUtilDatePattern == "dd.MM.yyyy" ) {
        this.day = parseInt( eliminateLeadingZero(regularExpressionResultsArray[ 1 ]) );
        this.month =  parseInt( eliminateLeadingZero(regularExpressionResultsArray[ 2 ]) ) - 1;
        this.year = parseInt( regularExpressionResultsArray[ 3 ] );
        return;
    }

    alert( "Date utility.  Date pattern not implemented " + this.dateUtilDatePattern );
}

function defineRegularExpression(){
    if ( ( this.dateUtilDatePattern == "M/d/yyyy" ) ||
         ( this.dateUtilDatePattern == "d/M/yyyy" ) ||
         ( this.dateUtilDatePattern == "dd/MM/yyyy" ) ||
         ( this.dateUtilDatePattern == "MM/dd/yyyy" ) ) {
        this.separator = "/";
        this.regExp = /^([0-9]{1,2})\/([0-9]{1,2})\/(\d\d\d\d)$/;
        return;
    }
    if ( ( this.dateUtilDatePattern == "d.M.yyyy" ) ||
         ( this.dateUtilDatePattern == "dd.MM.yyyy" ) ) {
        this.separator = ".";
        this.regExp = /^([0-9]{1,2})\.([0-9]{1,2})\.(\d\d\d\d)$/;
        return;
    }

    alert( "Date utility.  Date pattern not implemented " + this.dateUtilDatePattern );
}


function generateDateObject(dateAsString){

    // assert if the pattern matches
    if( dateAsString.search( this.regExp ) == -1 ){
        throw new DateUtilityException( this.ERROR_NOT_A_DATE );
    }

    // parse the string
    var regularExpressionResultsArray = this.regExp.exec( dateAsString );

    // set date components for datePattern
    this.setDateComponents(regularExpressionResultsArray);
    // Create the date object, and validate numbers are reasonable  
    if( (-1 < this.month) && (this.month < 12) ) {
        if( (0 < this.day) && (this.day < 32) ) {
            var goodDate = performThoroughComponentAnalysis(this.month,this.day,this.year);
            if (goodDate) {                 
                this.dateObject = new Date( new Number( this.year ), new Number( this.month ), new Number( this.day ) );                                        
                // standardize the format
                this.generateStandardizedDateAsStringAndDateComponents();
                return true;
            }
        }
    }
    throw new DateUtilityException( this.ERROR_NOT_A_DATE );
}

function performThoroughComponentAnalysis(month,day,year) {
    var monthB1 = month + 1; //Use month range 1-12

    // FEB
    if (monthB1 == 2) {
        // determine if leap year
        var div4 = false;
        var div100 = false;
        var div400 = false;
        var leapyear = false;
        if ((year % 4) == 0) {
            div4 = true;
        }            
        if ((year % 100) == 0) {
            div100 = true;
        }
        if ((year % 400) == 0) {
            div400 = true;
        }

        if (div4) {
            leapyear=true;
            if ((div100)&&(!div400)) {
                leapyear=false;
            }
        }

        if (leapyear) {
            if (day > 29) {
                return false;
            }
        } 
        else { 
            if (day > 28) {
                return false;
            }
        }
    }

    // 31 day months    
    if ( (monthB1 == 1)||(monthB1 == 3)||(monthB1 == 5)||(monthB1 == 7)||(monthB1 == 8)||(monthB1 == 10)||(monthB1 == 12) ) {
        if (day > 31) {
            return false;
        }
    }

    // 30 day months
    if ( (monthB1 == 4)||(monthB1 == 6)||(monthB1 == 9)||(monthB1 == 11) ) {
        if (day > 30) {
            return false;
        }
    }
    return true;
}

答案 1 :(得分:0)

如果输入日期正确,您的日期比较应该有效,最好使用某些输入小部件作为日期或输入 type =&#34; date&#34; 。我通过更改您的代码创建了工作示例。

/**
 *Function checks date is in past or future 
 */
function checkDate(){

  var realDate = new Date();
  var startDate = new Date($('#date').val());
  if (realDate >= startDate) {
      $('#infobros').removeClass('hidden');
      return false;//date in past
  }else{
      $('#infobros').addClass('hidden');
      return true;//date in future
  }
}

function validateForm(e){

    //use it on submit
    if (checkDate()){
      return true; //here date is in future so ok
    }
    else
        {
          e.preventDefault(); //stop submitting form
          alert("You date should be future date");
          return false;
        }
} 


$(document).ready(function(){
    $("#date").change(function(){

        checkDate();//use it on change

    });

    $("form").submit(validateForm);//set on submit event

    checkDate();//use it after start of page
});

以下是plunker中的工作代码 - https://plnkr.co/edit/fGGgHSiYcG1gqugLRToX?p=preview

答案 2 :(得分:0)

如果您要求的是如何比较日期,那么

if( realDate.getTime() >= startDate.getTime() ) {
    $('#infobros').removeClass('hidden');
}else{
    $('#infobros').addClass('hidden');
}