1

我试图在单击按钮时显示昨天日期,但为什么将日期显示为“ 2013-6-0”而不是2013-05-31

谁能告诉我我做错了什么

<!DOCTYPE html>
<html>
<head>
<script>
function displayDate()
{

var d = new Date();
var curr_date = d.getDate()-1;
var curr_month = d.getMonth() + 1;
var curr_year = d.getFullYear();
var yesterday = curr_year + "-" + curr_month + "-" + curr_date ;

document.write(yesterday);

}
</script>
</head>
<body>


<p id="demo">Click Button to Display Yesterday Date</p>

<button type="button" onclick="displayDate()">Display Date</button>

</body>
</html> 
4

4 回答 4

4

您应该更新并参考减去 1 天的日期:

var d = new Date();

d.setDate(d.getDate() - 1); // <-- add this to make it "yesterday"

var curr_date = d.getDate(); // <-- don't subtract 1 anymore
var curr_month = d.getMonth() + 1;
var curr_year = d.getFullYear();

演示

于 2013-06-01T17:32:46.220 回答
1

您的代码只需要一个天数(如 1、2、...)并从中减去一个。为什么你会期望它自动将日期回滚到上个月?

您可以通过从给定日期减去毫秒来生成新日期。尝试这个:

var today = new Date();
# subtract milliseconds representing one day from current date
var yesterday = new Date(today - 24*60*60*1000);
于 2013-06-01T17:34:13.523 回答
0
var today = new Date();
var yesterday = new Date();
yesterday.setDate(today.getDate()-1);

var yesterdayStr = yesterday.getFullYear() + "-" + (yesterday.getMonth()+1) + "-" + yesterday.getDate();
于 2013-06-01T17:38:06.323 回答
0
function displayDate()
{
    var today = new Date();
    today.setDate(today.getDate()-1);
    var yyyy = today.getFullYear().toString();
    var mm = (today.getMonth()+1).toString();         
    mm = mm.length==2?mm:"0"+mm;
    var dd = today.getDate().toString();
    dd = dd.length==2?dd:"0"+dd;
    var yesterday = yyyy+"-"+mm+"-"+dd;

    document.write(yesterday);
}
于 2015-01-16T23:47:40.377 回答