我试图在点击按钮时显示昨天日期,但为什么将日期显示为“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>
答案 0 :(得分: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();
<强> DEMO 强>
答案 1 :(得分:0)
您的代码只需要一天的数字(如1,2,......)并从中减去一个。为什么你会期望自动将这一天回滚到上个月?
您可以通过从给定日期减去毫秒来生成新日期。试试这个:
var today = new Date();
# subtract milliseconds representing one day from current date
var yesterday = new Date(today - 24*60*60*1000);
答案 2 :(得分:0)
var today = new Date();
var yesterday = new Date();
yesterday.setDate(today.getDate()-1);
var yesterdayStr = yesterday.getFullYear() + "-" + (yesterday.getMonth()+1) + "-" + yesterday.getDate();
答案 3 :(得分: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);
}