[RESOLVED]How to check length of DateTime.getFullYear() in Javascript when Day,Month,Year is coming from Model.

I have a 3 textboxes for Day, Month, Year & a corresponding property in my model which gets passed to the getAge() JS function through knockout using the below:

self.Age = ko.computed(function () {
                return getAge(new Date(this.DateOfBirthYear() + '/' + this.DateOfBirthMonth() + '/' + this.DateOfBirthDay()));
            }, this);

I had used the below to calculate age.

// Calculates the age based on the submitted DoB
        function getAge(dateOfBirth) {
            var today = new Date();
            var age = 0;
                      
            if (dateOfBirth.getFullYear().toString().length > 3) {
                age = today.getFullYear() - dateOfBirth.getFullYear();
            }
            var m = today.getMonth() - dateOfBirth.getMonth();

            if (m < 0 || (m === 0 && today.getDate() < dateOfBirth.getDate())) {
                age--;
            }

            return age;
        }

And based on the age i have to toggle a div if age > 50.

Now the problem is in IE & firefox, as soon as i enter 1 in the year box, the div shows up. while in chrome its fine.

Early finding say that in IE & Firebox the year is going as 1900 while in chrome its 2000, even if i am using getFullYear().

So not able to make it work, any suggestions.

Hi,

Don’t call the getAge() function until the
this.DateOfBirthYear() returns a string which is of length > 3.

Tried this, not working

self.Age = ko.computed(function () {
                if (this.DateOfBirthYear().length > 3) {
                    return getAge(new Date(this.DateOfBirthYear() + '/' + this.DateOfBirthMonth() + '/' + this.DateOfBirthDay()));
                }
            }, this);

My bad, working fine with the below code:

self.Age = ko.computed(function () {
                // call the getAge() function only when this.DateOfBirthYear() returns a string which is of length > 3.
                if (this.DateOfBirthYear() != null && this.DateOfBirthYear().toString().length > 3) {
                    return getAge(new Date(this.DateOfBirthYear() + '/' + this.DateOfBirthMonth() + '/' + this.DateOfBirthDay()), this.DateOfBirthYear());
                }
            }, this);

Leave a Reply