如何在datepicker上获取日期?

时间:2012-06-06 08:31:44

标签: javascript grails groovy datepicker

我是javascript和jquery的新手。我想通过datepicker获取用户选择的日期值,并使用我的javascript中的值。我的datepicker的名字是birthDate。这是日期选择器的html代码:

       <guis:datePicker required="true" label="Birthdate"
           bean="${accountInfo}" field="birthDate"
           value="${accountInfo?.birthDate?:"none"}"
           noSelection="${['null':'']}"/> 

我的javascript是:

            <script type="text/javascript">                      
                function isOfLegalAge() {    
                  var currDate = new Date();
                  var birthDate = $("#datepicker").val();  
                  var diff = currDate - birthDate
                  alert (currDate);
                  alert(birthDate);                      
                      if(diff >= 18){
                          return true;                              
                      }else {                         
                          alert("You must be atleast 18 years old to register!");
                          document.location.href = '/user';
                          return false;                          
                      }
                      return true;
                }
           </script>

datepicker返回的值采用以下格式:

Wed Jun 13 00:00:00 PHT 1990

..而新的日期是:

2012年6月6日星期三17:08:52 GMT + 0800(PHT)

请帮忙!

谢谢!

4 个答案:

答案 0 :(得分:3)

正如您所说,您以dd/mm/yyyy格式获得了日期,请尝试使用

var myDate = "06/06/2012";
var currentDate = new Date();
var compareDate = currentDate.getDate() + "/" + currentDate.getMonth() + "/" + currentDate.getFullYear();
if (myDate == compareDate)
    alert("Both dates are equal!");
else
    alert("Dates mismatch!");

如果你也在使用jQuery,你可以这样做:

var date = '06/06/2012';
var arrDate = date.split("/");
var today = new Date();
useDate = new Date(arrDate[2], arrDate[1] -1, arrDate[0]);

if (useDate == today)
    alert("Both dates are equal!");
else
    alert("Dates mismatch!");

希望这能帮到你!

答案 1 :(得分:2)

如果你在#datepicker id元素中有它,你可以使用val获取值并将其转换为Date,如下所示:

new Date( $('#datepicker').val() )

这会让你回到Wed Jun 20 2012 00:00:00 GMT+0100 (BST):)

干杯!

答案 2 :(得分:2)

试试这个

<form:input cssStyle="background-image:url('../images/DateCal.png'); 
                               background-repeat:no-repeat; background-position: right;" 
                               path="requirementDate" id="datepicker1" 
                               />

  $(document).ready(function() {
      var dates= $( "#datepicker1" ).datepicker({
            changeMonth: true,
            changeYear: true,
            yearRange: '2012:2022'

        });

  });

答案 3 :(得分:1)

试试这个:

var date = $('#datepicker').datepicker({ dateFormat: 'dd-mm-yy' }).val();