Search code examples
javascriptjquerytapestry

How to change a particular value when I select a date?


The requirement is I have two date fields:

  • One is effective date and date of birth. When I select the effective date on the page.
    The age field should do the following calculation.
    That is age would be Effective date - date of birth. the result should be set to the age field.

How to do in javascript or JQuery?

I'm using tapestry front end. So in the HTML page I want to do this setting of value to age field.


Solution

  • You need to convert your dates into milliseconds and subtract them, then calculate the age.

    HTML

    <input type="date" id="effective" />
    <input type="date" id="born" />
    

    jQuery

    function getTime(date){
        var dateArr = date.split('-');
        return new Date(dateArr[0], dateArr[1], dateArr[2]).getTime();
    }
    function calcDate(date1,date2) {
        var eff_date = getTime(date1);
        var born_date = getTime(date2);
    
        var diff = Math.floor(eff_date - born_date);
    
        var day = 1000* 60 * 60 * 24;
    
        var days = Math.floor(diff/day);
        var months = Math.floor(days/31);
        var years = Math.floor(months/12);
        return years
    }
    
    $("input[type=date]").change(function(){
        if($("#effective").val() != "" && $("#born").val() != ""){
            var age = calcDate($("#effective").val(),$("#born").val())
            alert(age);
        }
    });
    

    Check out this Fiddle..