简体   繁体   中英

how to calculate age from date of brith and store it in the database

I want to calculate age in years from date of birth and store it in my age column in my database below is what i have done so far. i have added images of the database and my date of birth on my page.I want to calculate on store it into the database without displaying the age on my page.Thanks in advance

 <div class="form-group">
     label for="date_of_birth">Date of birth</label>

 <div class="input-group date form_date col-md-5" data-date="" data-date-format="dd MM yyyy" data-link-field="dtp_input2" data-link-format="yyyy-mm-dd">

    <input type="text" class="form-control" value="<?php if(isset($date_of_birth)) echo $date_of_birth; ?>" size="16" readonly>
    <span class="input-group-addon"><span class="glyphicon glyphicon-remove"></span></span>
    <span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span>
             </div>

    <input type="hidden" id="dtp_input2" name="date_of_birth" value="<?php if(isset($date_of_birth)) echo $date_of_birth; ?>" /><br/>
            </div></div>

<script type="text/javascript" src="jquery/jquery-1.8.3.min.js" charset="UTF-8"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/bootstrap-datetimepicker.js" charset="UTF-8"></script>

<script type="text/javascript">
    $('.form_datetime').datetimepicker({
        //language:  'fr',
        weekStart: 1,
        todayBtn:  1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        showMeridian: 1
    });
    $('.form_date').datetimepicker({
        language:  'fr',
        weekStart: 1,
        todayBtn:  1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        minView: 2,
        forceParse: 0
    });
    $('.form_time').datetimepicker({
        language:  'fr',
        weekStart: 1,
        todayBtn:  1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 1,
        minView: 0,
        maxView: 1,
        forceParse: 0
    });
</script>

image for my date of birth

image for my database fields

You can add or subtract dates with JavaScript - if they are formatted as dates:

 const birthDate = new Date('1980.02.18') const today = new Date(Date.now()) console.log('birth date:', birthDate) console.log('today:', today) console.log('age in years:', new Date(birthDate - today).getYear())

This is a simple process, so as @NigeRen wrote: "Storing the age in the database is not good idea."

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