在我的程序中,通过提示值,我正在计算出生年份、下一年、天、小时、分钟和秒。现在我想计算这个人从出生之日起已经活了多长时间。为此,我做了下面的计算,但我对存活天数、小时、分钟、秒数的计算显示不正确。有人可以帮忙吗?
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var today = new Date();
var myMonth = prompt("What month were you born in?");
var myDay = prompt("What day were you born on?");
var myYear = prompt("What year were you born in?");
var birthday = new Date(myYear, myMonth, myDay);
var dateLoc = document.getElementById("dateField").innerHTML = "Today is " + today;
var birthField = document.getElementById("birthField")
.innerHTML = "I was born on " + monthNames[myMonth - 1] + ' ' + myDay + ', ' + myYear + '.' +
'(' + myMonth + '/' + myDay + '/' + myYear + ')';
var milliseconds, seconds, minutes, hours, days;
var years = today.getFullYear() - birthday.getFullYear();
myMonth--;
var nextBirthday = (new Date(today.getFullYear(), myMonth, myDay)) < today ? (new Date(today.getFullYear() + 1, myMonth, myDay)) : (new Date(today.getFullYear(), myMonth, myDay))
console.log(nextBirthday);
milliseconds = diff % 1000;
diff = (diff - (milliseconds)) / 1000;
seconds = diff % 60
diff = (diff - seconds) / 60;
minutes = diff % 60
diff = (diff - minutes) / 60;
hours = diff % 24
days = (diff - hours) / 24;
var nextBirth = document.getElementById("nextBirth").innerHTML = "I am " + years + " Years old, and will turn " + (years + 1) + " in:" + "<br>" + days + " days, " + hours + " hours, " + minutes + " minutes, " + seconds + " seconds";
milliseconds = diffAlive % 1000;
diffAlive = (diffAlive - (milliseconds)) / 1000;
seconds = diffAlive % 60
diffAlive = (diffAlive - seconds) / 60;
minutes = diffAlive % 60
diffAlive = (diffAlive - minutes) / 60;
hours = diffAlive % 24
days = (diffAlive - hours) / 24;
var aliveFor = document.getElementById("aliveFor").innerHTML = "I have been alive for..." + "<br>" + days + " days, " + hours + " hours, " + minutes + " minutes, " + seconds + " seconds";
p {
text-align: center;
font-family: monospace;
font-size: 20px;
}
body {
background-image: url(birth.jpg");
background-repeat: no-repeat;
background-size: 1300px 600px;
}
<p id="dateField"> </p>
<p id="birthField"> </p>
<p id="nextBirth"> </p>
<p id="aliveFor"> </p>
输出:
最佳答案
您传递给 Date
的月份错误计算生日
时的构造函数。它是从 0 开始的。
将 myMonth--
行移至设置生日变量之前。
例如
myMonth--;
var birthday = new Date(myYear, myMonth, myDay);
关于Javascript:计算从出生年份到今天的天、小时、分钟、秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46762699/