剛剛js做項目,遇到需要獲取昨天日期的問題,網上找了下答案,感覺網上的答案都不太嚴謹,自己寫了個,湊合能用吧,忘大神們拋磚指教.
<script type="text/javascript" language="javascript"> function getYestoday(date){ var arrMonth = new Array([0], [31], [28], [31], [30], [31], [30], [31], [31], [30], [31], [30], [31]);//初始化月份(第一個0,占位作用,讓下標和月份對應) var strYear = date.getFullYear();//獲取年份 var strDay = date.getDate();//獲取日期 var strMonth = date.getMonth() + 1;//獲取月份 ///判斷是否是閏年 if (strYear % 4 == 0 && strYear % 100 != 0) { arrMonth[2] = 29; } ///判斷日期是否是第一天 if (strDay - 1 == 0) { ///判斷月份是否是一月 if (strMonth - 1 == 0) { strYear -= 1; strMonth = 12; } else { strMonth -= 1; } strDay = arrMonth[strMonth]; } else { strDay -= 1; } ///月份小於10,前面加0 if (strMonth < 10) { strMonth = "0" + strMonth; } ///日期小於10,前面加0 if (strDay < 10) { strDay = "0" + strDay; } return strYear + "-" + strMonth + "-" + strDay; } alert(getYestoday(new Date("2012-1-1")));//測試日期 </script>