gpt4 book ai didi

javascript - 如何使用 Date 对象从提示中获取月份名称,然后计算下一个生日

转载 作者:行者123 更新时间:2023-11-28 13:05:35 25 4
gpt4 key购买 nike

在我的 javascript 程序中,我试图计算出生年份。我创建了接受不同值的提示对话框,并且我正在显示这些值,但用户给出的月份值在第二行中显示不正确。用户输入了 8,显示的是 10 月。谁能帮我找出问题?我应该如何从提示中获取所有三个值来计算出生年份?

代码:

var today = new Date();

var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];

var birth = 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 days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var dateLoc = document.getElementById("dateField").innerHTML = "Today is " + today;

var birthField = document.getElementById("birthField")
.innerHTML = "I was born on " + monthNames[birth.getMonth()] + ' ' + myDay + ',' + myYear + '.' +
'(' + myMonth + '/' + myDay + '/' + myYear + ')';


var secondsBetween = (endDate.getTime() - startDate.getTime()) / 1000
endDate = new Date(today.getFullYear() + 1, myMonth, myDay);
var nextBirth = document.getElementById("nextBirth").innerHTML = "I am" + endDate + "Years old, and will turn"+ +"in" ;
<p id="dateField"> </p>
<p id="birthField"> </p>
<p id="nextBirth"> </p>

输出:

enter image description here

最佳答案

您的 monthNames[birth.getMonth()] 存在问题,请尝试使用 monthNames[myMonth - 1]:

    var birthField = document.getElementById("birthField")
.innerHTML = "I was born on " + monthNames[myMonth - 1] + ' ' + myDay + ',' + myYear + '.'
+ '(' + myMonth + '/' + myDay + '/' + myYear + ')';

October 是当前月份名称,这是由于 birth = new Date()

您的下一个生日可以通过 (myMonth - 1)/myDay/(今天的年份 + 1) 获得。然后计算两个日期之间的秒数,您可以使用

var secondsBetween = (endDate.getTime() - startDate.getTime()) / 1000

这意味着您必须将输入日期转换为 javascript 日期。在你的情况下(就在 specification 后面),这非常简单:

endDate = new Date(today.getFullYear() + 1, myMonth - 1, myDay);

关于javascript - 如何使用 Date 对象从提示中获取月份名称,然后计算下一个生日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46721303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com