2

I've managed to calculate age using only "Year", but I would like to know how you can do this using a complete date ( YYMMDD ),

This is the code I used to calculate age using only year:

function Onclick() {
var Text1 = $("#Text1").val();
var datetoday = new Date();
var today = datetoday.getFullYear();
var datebirthday = new Date();
datebirthday.setFullYear(Text1);
var birthday = datebirthday.getFullYear();
var age = today - birthday;
Dr Cox
  • 445
  • 1
  • 4
  • 22

2 Answers2

4

That should work for you. First it does a Year compare, then reduces a year if the months or days do not align.

Edit: The expected Date format is 'YYYY/MM/DD'

function Onclick() { 
        var today = new Date();
        var birthDate = new Date($("#Text1").val());
        var age = today.getFullYear() - birthDate.getFullYear();
        var m = today.getMonth() - birthDate.getMonth();
        if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
            age--;
        }
}

The correct age is stored in the age variable. Heres a good thread about it: https://stackoverflow.com/questions/4060004/calculate-age-in-javascript

Benjamin Chase
  • 151
  • 1
  • 5
1

setFullYear takes 3 parameters for Year, Month , Day
Be aware in Javascript Months start at 0 for january, so 11 is december!!

Date.setFullYear(year,month,day)

If there is no issue to add extra libraries, then add MomentJS, this helps a lot in working with dates.

In Can anyone color code a column with an if statement? the javascript Today calculation is done inside a Calculated Column Formula (can only be used in Views, does not work on Forms) and colors the View Items based on a Date range.

Danny '365CSI' Engelman
  • 21,176
  • 7
  • 35
  • 79