2014-08-30 49 views
0

首先我使用從java腳本傳遞數據到動作類但是我想在java腳本中做如何做?如何在JavaScript中以dd-Mon-yyyy格式檢查日期?

jsp的Java腳本:

$('#nwr_fa_dob').keypress(function(event) 
     { 
      $('#nwr_fa_gender').attr('disabled',false); 
     var keycode = (event.keyCode ? event.keyCode :event.which); 
     var dob= $('#nwr_fa_dob').val(); 
     if(keycode == '13' || keycode =='40') 
     { 
      $.ajax({ 
       type: "POST",    
       dataType: "json", 
       url: "dob_details", 
       data: {dob:dob},   
       success: function(response) 
       { 
        $('#nwr_fa_dob').val(response.dob); 
        if($('#nwr_fa_dob').val()==null || $('#nwr_fa_dob').val()=='') 
        { 
         alert("You Will Give Age or DateFormat of dd-MMM-yyyy(Ex : 18-Mar-1990)"); 
         $('#nwr_fa_dob').val(''); 
         $('#nwr_fa_dob').focus(); 
         } 
        else 
        { 
         $('#nwr_fa_dob').val(response.dob); 
         $('#nwr_fa_gender').focus(); 
         } 
        } 
       }); 
      return false; 
      } 
     if(keycode=='38'){ 
      $('#nwr_fa_fsname').focus(); 
      return false; 
      } 
     }); 

Java代碼:

public String dob_fetchdate() { 
     try { 
      if (dob.length() == 11) { 
       Date dat = ymd.parse(dob); 
       if (ymd.format(dat).equals(dob)) { 
        dob = dob; 
       } else { 
       dob = null; 
       } 
      } else if (dob.length() == 10) { 
       dob = null; 
      } else if (dob.length() == 2) { 
       String date = DateNow.substring(7, 11); 
       String year = String.valueOf(Long.valueOf(date) 
         - Long.valueOf(dob)); 
       dob = DateNow.substring(0, 7).concat(year); 
      } else { 
       dob = null; 
      } 
      return "success"; 
     } catch (Exception ex) { 
      System.out.println("Dob Error =" + ex); 
      return "error"; 
     } 
    } 

回答

1

moment.js(http://momentjs.com/)肯定是在JavaScript日期操作參考API。 下面是它如何能在你的情況下使用的例子:

var userDateString = "30-Aug-2014"; 
var dateFormat = "DD-MMM-YYYY"; 
var myMoment = moment(userDateString, dateFormat); 
if (myMoment.isValid()) { 
    alert ("Date is valid !"); 
} else { 
    alert ("Invalid date !"); 
} 

它也可以告訴你,什麼是錯的,你輸入的日期。

0

它可以很容易地與正則表達式來完成在JavaScript

var date="01-01-1944"; 
    var pattern = /[0-9]{2}[-]{1}[0-9]{2}[-]{1}[0-9]{4}/i; 

    if(pattern.test(date)) { 
     var dateParts = date.split("-"); 
     // You can do the range checking here 
     console.log(dateParts[0]); 
     console.log(dateParts[1]); 
     console.log(dateParts[2]); 
    } 

要知道在JS更多關於正則表達式遵循this

又讀了這個問題Regular Expression to match valid dates的答案。