Ishan
Ishan

Reputation: 4028

Given a start date , how to calculate number of years till current date in javascript

I have a start date value to be entered in a textbox in dd/mm/yyyy format, and as soon as value is entered in it, i want to fire onchange event for that textbox and and use current date to calculate number of years passed.

How can i do this in JavaScript, i have implemented in C#. is there any function in javascript which will help me calculate number of years between two dates?

Upvotes: 0

Views: 674

Answers (3)

Ishan
Ishan

Reputation: 4028

Here i got the solution

Calculate age in JavaScript

function getAge(dateString) {
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}

Upvotes: 1

Willem D&#39;Haeseleer
Willem D&#39;Haeseleer

Reputation: 20180

You can parse the date manually and then use getFullYear() to calculate the difference. You can also use a library to parse the date, like jQuery UI

http://docs.jquery.com/UI/Datepicker/formatDate

Upvotes: 0

Royi Namir
Royi Namir

Reputation: 148514

you cant with d/m/yyyy

d/m/yyy should be ISO compatible i.e : yyyy-mm-dd

var g="22/12/1978".split('/')

 new Date().getFullYear()- new Date(g[2]+"/"+g[1]+"/"+g[0]).getFullYear()

Upvotes: 0

Related Questions