14

I want to compare the user's birthday against today's date and get the number of days in between. The birthday they enter will be in the form of 12/02/1987 in an input box of type text

In my JS file I have code that looks like this:

function validateDOB(element) {
var valid = false;

var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //do that January is NOT represented by 0!
var yyyy = today.getFullYear();

if (dd < 10) {
    dd = '0' + dd
}
if (mm < 10) {
    mm = '0' + mm
}

var today = mm + '/' + dd + '/' + yyyy;
alert(today);
if (element.value != today) {
    var days = 0;
    var difference = 0;

    Christmas = new Date("December 25, 2011");

    today = new Date();

    difference = today - Christmas

    days = Math.round(difference / (1000 * 60 * 60 * 24)-1);
    alert(days); 
    valid = true;
}

Instead of using "Christmas" I want to compare element.value... how do I do this?

When I put difference = today - element.value it won't show me the difference. The alert box comes up as NaN.

Jan Turoň
  • 31,451
  • 23
  • 125
  • 169
BigBug
  • 6,202
  • 23
  • 87
  • 138
  • possible duplicate of [Compare 2 dates with JavaScript](http://stackoverflow.com/questions/492994/compare-2-dates-with-javascript) – Widor Nov 02 '11 at 23:23
  • 1
    @widor no, my Q is specific... – BigBug Nov 02 '11 at 23:25
  • 1
    Your question is specific, yes, but that question answers it. – Blender Nov 02 '11 at 23:26
  • @Blender - The real question (despite its title) seems to be "Why does `difference = today - element.value` return `NaN`?". The linked question is trying to determine if one date is greater than, less than, or equal to another date. This question is about determining the number of days between two dates. The date comparison is already being done correctly here so that answer doesn't really help. The real answer is to parse the string to a Date before comparing. – gilly3 Nov 02 '11 at 23:42
  • Does this answer your question? [How to calculate number of days between two dates?](https://stackoverflow.com/questions/542938/how-to-calculate-number-of-days-between-two-dates) – starball Aug 11 '23 at 23:30

2 Answers2

142

I wrote a lightweight date library called Moment.js to handle stuff like this.

var birthday = moment('12/02/1987', 'MM-DD-YYYY');
var inputDate = moment(element.value, 'MM-DD-YYYY');
var diff = birthday.diff(inputDate, 'days'); 

http://momentjs.com/docs/#/displaying/difference/

Peter Brown
  • 50,956
  • 18
  • 113
  • 146
timrwood
  • 10,611
  • 5
  • 35
  • 42
  • not sure how well "lightweight" aged (https://github.com/moment/moment/issues/3376). Also, https://momentjs.com/docs/#/-project-status/ – starball Aug 11 '23 at 23:28
11

You'll need to first parse element.value as a date:

difference = today - new Date(element.value);

http://jsfiddle.net/gilly3/3DKfy/

gilly3
  • 87,962
  • 25
  • 144
  • 176