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;
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

  • Using your code, which format do i enter the date in? YYYY/MM/DD? – Dr Cox Jul 21 '15 at 12:16
  • I updated the answer for you, but YYYY/MM/DD is correct. But you can use anything that Date() accepts. See: w3schools.com/jsref/jsref_obj_date.asp – Benjamin Chase Jul 21 '15 at 12:23
  • Thank you! it works perfectly, and thank you for the link. – Dr Cox Jul 21 '15 at 12:29
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.