0

I'm working on a web site which contain a form; in that form i ask the users to introduce their birthday date and i want to calculate their age automatically but i have a problem with the format of the date introduced by the user which is DD/MM/YYYY and i want to convert the format of the date now to the same.

here's the code i wrote:

 function calculAge()  
{
var a = new Date();
a = document.getElementById("dat").value ;
var b = new Date();
 var c = b - a;
 c = Math.round(c / (1000 * 60 * 60 * 24));
 alert(c);
 document.getElementById("age").innerHTML = "Votre age est "+c; 
}

Thanks

Roro Sweer
  • 35
  • 4
  • `a` is a string, `b` is a `Date`. So basically trying to subtract one from the other is like comparing apples to oranges. Such operation is not defined. You will need to first parse the string user input before performing any operations on it. – Darin Dimitrov Dec 05 '15 at 21:30
  • It's like subtracting women from department stores, it just can't be done – adeneo Dec 05 '15 at 21:30
  • Can we have an example of what `a` would look like? – Nick Zuber Dec 05 '15 at 21:30
  • On the other hand, if you make your users give their age in milliseconds, your code works just fine -> http://jsfiddle.net/4ywzrtsu/ – adeneo Dec 05 '15 at 21:38
  • This question is always have [solution](http://stackoverflow.com/questions/4060004/calculate-age-in-javascript) on StackOverflow. – Ronin Dec 05 '15 at 21:39
  • @Rahma Marref - Try this: [JsFiddle get age from date link](http://jsfiddle.net/n33RJ/615/) – DMSJax Dec 05 '15 at 21:40
  • @DMSJax Comments aren't a place for answers. And please don't copy other peoples answers – Cjmarkham Dec 05 '15 at 21:47

4 Answers4

1

You could convert the user date to milliseconds and work from there:

var userDate = '11/11/1986';

var parts = userDate.split('/');
userDate = Date.UTC(parts[2], parseInt(parts[1], 10) - 1, parts[0]);
var diff = Date.now() - userDate;
var date = new Date(diff);

console.log(date.getUTCFullYear() - 1970);
Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
  • The expression `parseInt(parts[1], 10) - 1` can be just `parts[1] - 1` since the `-` operator will coerce values to number anyway. ;-) – RobG Dec 05 '15 at 21:47
0

DD/MM/YYYY is not a standard date (et oui, je connais cette douleur...) so you have to hack a bit :

 function f() {
   var t = document.getElementById("date").value.split('/');
   console.log(t);
   var a = new Date(t[2],t[1],t[0]);
   console.log(a);
   var b = new Date();
   console.log(b);
   var c = b - a;
   c = Math.round(c / (1000 * 60 * 60 * 24 * 365));
   alert(c);
   document.getElementById("age").innerHTML = "Votre age est " + c;
 }
<input id="date" value="22/11/1995"/><br>
<div id="age" ></div><br>

<button onclick="f()">run</button>
Blag
  • 5,818
  • 2
  • 22
  • 45
0

In your code:

var a = new Date();

Assigns a Date to a.

a = document.getElementById("dat").value ;

Assuming dat is a form control, this assigns a string to a, the Date is now available for garbage collection.

var b = new Date();

Assigns a Date to b.

var c = b - a;

Attempts to subtract a string from a Date. The - operator will attempt to convert the expressions to numbers, b will be converted to its time value, if a is a date in the format DD/MM/YYYY then it will return NaN. Any value minus NaN returns NaN.

What you need to do is parse the value of a to be a Date object, there are many questions here on how to do that (you only need a 4 line function that will also validate the date, e.g. Date('2015-1-1') outputs different from Date(2015-01-01)).

Once a and b are valid Dates, then the subtraction will work and:

c = Math.round(c / (1000 * 60 * 60 * 24));

will give you the number of days between the two dates. Note that rounding may tip the value one way or the other by 1 day when you weren't expecting it. If you want whole days, better to set the time to say 00:00:00 on both dates, then subtract and round.

Community
  • 1
  • 1
RobG
  • 142,382
  • 31
  • 172
  • 209
-1

This might be an easier approach for you:

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;
}
alert('age: ' + getAge("1980/08/10"));
DMSJax
  • 1,709
  • 4
  • 22
  • 35
  • OP use European date DD/MM/YYYY so your answer don't work ;) – Blag Dec 05 '15 at 21:43
  • Its worth noting that this answer was copied from here http://stackoverflow.com/questions/10008050/get-age-from-birthdate – Cjmarkham Dec 05 '15 at 21:44
  • @carl thats true, but its an answer (which incidentally OP could have found on his own) – DMSJax Dec 05 '15 at 21:46
  • You shouldn't use the Date constructor to parse strings, it's unreliable and in this case, will produce incorrect results. Date strings should always be manually parsed. – RobG Dec 05 '15 at 21:49
  • It is plagiarism regardless of your reasons – Cjmarkham Dec 05 '15 at 21:49
  • @Blag—I think you meant "non–US date format", since nearly everywhere other than the US uses d/m/y, though some use y/m/d. :-) – RobG Dec 05 '15 at 21:50
  • @RobG I was trying to not be too rude XD but yes, I don't even understand that this `d/m/y` can not be parsed out of the box (f*** the US and their retard units <_>) – Blag Dec 05 '15 at 21:54