刚刚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>