需要使用 javascript 来告诉我从当前日期到输入日期经过的天数、月数和年数

我有它,所以它会显示一个包含年、月和日的日期。但是当我输入我的生日时,它显示为 27 年 329 个月和 10299 天。我需要它显示 12 个月格式的月份和 31 天格式的日期。


`


    <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'

    }


慕的地8271018
浏览 96回答 1
1回答

Helenr

计算年差后,您需要修改所选日期的对象以具有相同的年份。这样,您可以计算月数/天数。<script>function handleDateChanged() {&nbsp; &nbsp; var data = document.getElementById("date").value;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var dateParts = data.split("/");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var pickedDate = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var currentDate = new Date();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var years = currentDate.getYear() - pickedDate.getYear();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pickedDate.setYear(pickedDate.getFullYear() + years);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(pickedDate);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var diff = Math.floor(currentDate.getTime() - pickedDate.getTime());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var day = 1000 * 60 * 60 * 24;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var days = Math.floor(diff/day);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var months = Math.floor(days/31);&nbsp; &nbsp; &nbsp; &nbsp;//&nbsp; &nbsp; &nbsp;var years = Math.floor(months/12);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("result").innerHTML = years + ' years, ' + months + ' months, ' + days + ' days'&nbsp; &nbsp; }</script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript