如何用javascript获取特定日期

时间:2015-11-13 03:47:07

标签: javascript

您好我正在尝试获取用户在表单中输入特定日期的具体日期,但输出不符合预期。我已经尝试了一些代码而不是工作,你能否通过查看这段代码告诉我有什么问题:

<code>
<!DOCTYPE html>
<html>
<head>
    <title> The day of your birthday</title>
</head>
<body>

<form>
<p> day :</p>
<input type="text" id="day"/>
<p> month :</p>
<input type="text" id="month"/>
<p> year :</p>
<input type="text" id="year"/><br/>


<input type="button" value="Check "onclick="dayBirthDay()"/>
<input type="reset" value="reset">
</form>
<p id="ok"></p>
<script type="text/javascript">

function dayBirthDay(){
    var t = new Date();
    var day = document.getElementById('day').value;
    var month = document.getElementById('month').value;
    var year = document.getElementById('year').value
    t.setDate(day);
    t.setMonth(month);
    t.setYear(year);
 // how to fix this?? i've try using monthDay. but both is don't seem logic
    var weekDay = ["Sunday", "Monday", "Tuesday","Wednesday","Thursday",     "Friday", "Saturday"]
    document.getElementById('ok').innerHTML = "you were born at " +    weekDay[t.getDay()];
}
    console.log(Date());


    </script>
    </body>
    </html>
</code>

3 个答案:

答案 0 :(得分:0)

我唯一能看错的是JS Date()中的月份是0,所以减去你给定的月份1:

t.setMonth(month-1);

答案 1 :(得分:0)

您的代码确实有效:

&#13;
&#13;
function dayBirthDay(){
    var t = new Date();
    var day = document.getElementById('day').value;
    var month = document.getElementById('month').value;
    var year = document.getElementById('year').value
    t.setDate(day);
    t.setMonth(month);
    t.setYear(year);
 
    var weekDay = ["Sunday", "Monday", "Tuesday","Wednesday","Thursday",     "Friday", "Saturday"]
    document.getElementById('ok').innerHTML = "you were born at " +    weekDay[t.getDay()];
}
&#13;
<p> day :</p> <input type="text" id="day"/>
<p> month :</p> <input type="text" id="month"/>
<p> year :</p> <input type="text" id="year"/><br/>

<input type="button" value="Check "onclick="dayBirthDay()"/>

<p id="ok"></p>
&#13;
&#13;
&#13;

我猜,由于setMonth问题,您收到了错误的结果。

请注意setMonth从0到11 取整数。因此,1月将是0,12月将是11。

答案 2 :(得分:0)

试试这段代码

&#13;
&#13;
function dayBirthDay(){
    var t = new Date();
    var day = document.getElementById('day').value;
    var month = document.getElementById('month').value;
    var year = document.getElementById('year').value
    t.setDate(day);
    t.setMonth(month);
    t.setYear(year);
 
    var weekDay = ["Sunday", "Monday", "Tuesday","Wednesday","Thursday",     "Friday", "Saturday"]
    document.getElementById('ok').innerHTML = "you were born at " +    weekDay[t.getDay()];
}
&#13;
<p> day :</p> <input type="text" id="day"/>
<p> month :</p> <input type="text" id="month"/>
<p> year :</p> <input type="text" id="year"/><br/>

<input type="button" value="Check "onclick="dayBirthDay()"/>

<p id="ok"></p>
&#13;
&#13;
&#13;