简体   繁体   English

Javascript-从字段获取日期并计算出生日期

[英]Javascript - get date from field and calculate date of birth

I have a field with a datepicker which is used on a date of birth text field. 我有一个带有日期选择器的字段,该字段用于出生日期文本字段。 I have also got an age text input which I would like to populate with their age upon the date of birth field information being entered (so it would compare against the current date and show the childs age) 我还输入了年龄文本,我希望在输入出生日期信息时用他们的年龄来填充(以便将其与当前日期进行比较并显示孩子的年龄)

I'm having a little bit of trouble creating the correct date format (dd-mm-yyyy) in JavaScript. 我在JavaScript中创建正确的日期格式(dd-mm-yyyy)时遇到了一些麻烦。 So far I have this. 到目前为止,我有这个。

HTML: HTML:

<label for="child_age">Age</label>
<p><input type="text" class="child_age" name="child_age" /></p>

<label for="child_dob">Date of Birth</label>
<p><input type="text" class="child_dob" name="child_dob" /></p>

JQUERY: JQUERY:

$(function () {
$(".child_dob").change(function(event){
        console.log();
        var d = new Date();
        var dob = $(this).val();
        console.log(dob); //shows the correct date from the datepicker (dd-mm-yyyy)
        console.log(d); //shows Tue Apr 30 2013 16:48:32 GMT+0100 (GMT Daylight Time) 
    });
});

How would I convert the date into the correct format and compare it against the information entered in the child_dob field? 如何将日期转换为正确的格式,并将其与child_dob字段中输入的信息进行比较?

To get the date selected in the datepicker, use the getDate method: 要获取在日期选择器中选择的日期,请使用getDate方法:

$(function () {
    $(".child_dob").change(function(event){
        console.log();
        var d = new Date();
        var dob = $(this).datepicker("getDate");
        console.log(dob);
        console.log(d);
    });
});

It might be better to put this code in the onSelect option of the datepicker rather than the change event of the form field. 最好将此代码放在onSelect选项中,而不要放在form字段的change事件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM