Search code examples
javascriptdatetimedifference

Need to use javascript to tell me elasped days,month, and years from current date to date entered


I have it so it will display a date with years, months, and days. But it is displaying when i put in my birthday as, 27 years, 329 months, and 10299 days. I need it to display, months in a 12 month format and days in a 31 day format.

`

    <p>
      <h2>Pick A Date!(dd/mm/yyyy</h2>
        <center><input id="date">
        <button onclick="handleDateChanged()">Calculate</button></center>
    </p>

    <p>
       <h2>It's been since: <span id="result"></span></h2>
    </p>

    function handleDateChanged() {
    var data = document.getElementById("date").value;
            var dateParts = data.split("/");

            var pickedDate = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]); 
            var currentDate = new Date();

            console.log(pickedDate);
            console.log(currentDate);

            var diff = Math.floor(currentDate.getTime() - pickedDate.getTime());
            var day = 1000 * 60 * 60 * 24;

            var days = Math.floor(diff/day);
            var months = Math.floor(days/31);
            var years = Math.floor(months/12);

            document.getElementById("result").innerHTML = years + ' years, ' + months + ' months, ' + days + ' days'
    }

`


Solution

  • After you calculate the years difference, you need to modify the object of the picked date to have the same year. This way, you can calcuate the months / days.

    <script>
    function handleDateChanged() {
        var data = document.getElementById("date").value;
                var dateParts = data.split("/");
    
                var pickedDate = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]); 
                var currentDate = new Date();
    
                var years = currentDate.getYear() - pickedDate.getYear();
                pickedDate.setYear(pickedDate.getFullYear() + years);
    
                console.log(pickedDate);
    
                var diff = Math.floor(currentDate.getTime() - pickedDate.getTime());
                var day = 1000 * 60 * 60 * 24;
    
                var days = Math.floor(diff/day);
                var months = Math.floor(days/31);
           //     var years = Math.floor(months/12);
    
                document.getElementById("result").innerHTML = years + ' years, ' + months + ' months, ' + days + ' days'
        }
    </script>