简体   繁体   中英

How to calculate age from given data on input field?

I have searched but i didn't get perfect solution of my issue.I can calculate age in normal way.But i haven't any idea how can i calculate age from given data on input field.I have used jQuery DatePicker for input field.My code:

$birthday = new DateTime('1970-02-01');
$to       = new DateTime('today');
echo $birthday ->diff($to)->y.' Years, '.$birthday ->diff($to)->m.' Months, '.$birthday ->diff($to)->d.' Days ';

This is my field:

在此处输入图片说明

Now i want $birthday will be dynamic and it will insert and want to show immediately age calculation without page load. Have any clue? Thanks in advance.

The jQuery datepicker displays the dates in an input field with id="datepicker" that you can use to get your date. For a client-side calculation, the momentjs library mentionned in other answer if perfect for this job.

 fromdate = $('#datepicker').val(); console.log(fromdate); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="text" id="datepicker" class="hasDatepicker" value="2016/14/12"> 

If you want to calculate server-side, you can pass the value to PHP without reloading page with Ajax:

$('#datepicker').change(function(){
    $.ajax({
        type: "POST",
        url: "datecalc.php",
        data: {text:$(this).val()}
    });
});

If you want to calculate the age in jQuery, you can use moment.js like this:

moment("05/05/1998", "MM/DD/YYYY").month(0).from(moment().month(0));
// Output = 22 years ago

 $(function() { var dob = $('.dob').val(); $('.dob').on('input', function(e) { var a = moment($(this).val(), "MM/DD/YYYY").month(0).from(moment().month(0)) console.log(a); }); var a = moment($('.dob').val(), "MM/DD/YYYY").month(0).from(moment().month(0)) console.log(a); }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class='dob' type='text' value="05/05/1996"> 

Inside your controller, you can use Carbon's age method like this:

$birthday = Carbon\Carbon::parse('1970-02-01');
$age = $birthday->age;
// Output - (int) 46

See Carbon Docs for reference

Hope this helps!

You need to read the value of the data input field using JQuery or Javascript and then pass the value to your age calculation function.

For example if your date field has id="date-picker", then you can read the date as $("date-picker").val() or document.getElementById("date-picker").value()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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