2013-06-01 107 views
1

我試圖在點擊按鈕顯示昨天的日期,但顯示昨天的日期爲什麼它的顯示日期爲「2013-6-0」 代替2013-05-31的JavaScript:在JavaScript

有誰請告訴我,我是做錯了什麼

<!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> 
+1

'd.getDate()'1,和'1 - 1 = 0',所以你能指望什麼如果不是0?你必須從整個日期減去1,而不僅僅是從日內的部分。 –

+0

爲什麼你在這個月加1? –

+0

@ExplosionPills好,如果不是在錯誤的時間完成的話,這是正確的做法:-) – Pointy

回答

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

+0

正確...並*然後*獲取顯示日期的部分。 – Pointy

+0

非常感謝 – Kiran

0

你的代碼只需要一天的數字(如1,2,...)並從中減去一個數字。你爲什麼期望自動將日期推回到前一個月?

您可以通過從給定日期減去毫秒來生成新日期。試試這個:

var today = new Date(); 
# subtract milliseconds representing one day from current date 
var yesterday = new Date(today - 24*60*60*1000); 
0
var today = new Date(); 
var yesterday = new Date(); 
yesterday.setDate(today.getDate()-1); 

var yesterdayStr = yesterday.getFullYear() + "-" + (yesterday.getMonth()+1) + "-" + yesterday.getDate(); 
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); 
}