Calculate age from date of birth

Calculate age from date of birth

BalaKrishnanDhanuskodiBalaKrishnanDhanuskodi Posts: 45Questions: 17Answers: 0

Happy Morning one and all,

I was trying to repeat "data":"dob" in two columns please refer code below, the first one is exact date of birth and the second one is to render data into age.

Data

Bala
Krishnan
999999999
balaxxxxxx@gmail.com
01-Feb-1981
01-Feb-1981

HTML

<th>Firstname</th>
<th>Lastname</th>
<th>Mobile</th>
<th>Email</th>
<th>DOB</th>
<th>DOB</th>

JS

(function($){
$(document).ready(function() {
var table = $('#2018_view').DataTable( {
columnDefs: [
 { targets: 5, data: 'dob', render:    function getAge(dateString) {
    var today = new Date();
    var birthDate = new Date(data.dob);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
} }}
 ],
    columns: [

              {
                "data": "firstname"
            },
            {
                "data": "lastname"
            },
            {
                "data": "mobile"
            },
            {
                "data": "email"
            },
            {
                "data": "dob"
            },
            {
                "data": "dob"
            } 
        ],
} );

I am sure - their is a JS coding error, unable to figure out - any help would be great full.

Replies

  • colincolin Posts: 15,112Questions: 1Answers: 2,583

    Hi @BalaTEST ,

    I'd recommend using moment.js for that, it would make much simpler.

    Cheers,

    Colin

  • allanallan Posts: 61,446Questions: 1Answers: 10,054 Site admin

    Personally I'd use MomentJS to do the difference calculation.

    Allan

  • BalaKrishnanDhanuskodiBalaKrishnanDhanuskodi Posts: 45Questions: 17Answers: 0

    Thanks Colin and Allan,

    Working solution with moment.js.

    JS moment.js - link in html.
    <script type="text/javascript" charset="utf-8" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

    JS
    columnDefs: [ { targets: 13, mRender: function ( data, type, row ) { return Math.floor(moment(row.timestamp).diff(data, 'years', true))}} ]

This discussion has been closed.