原理很简单,一天的时间的毫秒数是1000*60*60*24,前n天的日期就是现在日期换成毫秒-n*1000*60*60*24。再把这个值换成日期即可(通过setTime方法)
var newDate = new Date();
var end_date = ""+ newDate.getFullYear()+"-"+(newDate.getMonth()+1)+"-"+(newDate.getDate()+1)+""
$(".end_date").val(end_date);
var time = newDate.getTime();
var startdate = new Date(time - 60*1000*60*60*24);
var start_date = startdate.getFullYear()+"-"+ (startdate.getMonth()+1)+"-"+ startdate.getDate();
$(".start_date").val(start_date);
<body>
<select id="num"name="num"style="width:150px"οnchange="ff()">
<option value="-1">昨天</option>
<option value="0">今天</option>
<option value="1">明天</option>
</select><br>
<textarea id="ar"rows="3"cols="20">
haha
</textarea>
<br/>
<input type="text"value=""name="bday"id="bday"/>天之前
<input type="button"οnclick="bday()"value="计算"><br/>
<input type="text"value=""name="aday"id="aday"/>天之后
<input type="button"οnclick="aday()"value="计算"><br/>
</body>
<script>
ff();
functionff(){
varobj=document.getElementById("num");
varv1=obj.options[obj.selectedIndex].text;
varv2=obj.options[obj.selectedIndex].value;
vartvv=giveDateStr(getTargetday(v2));
document.getElementById('ar').innerText=tvv;
}
functionisInteger(obj) {
varr = /^\+?[1-9][0-9]*$/; //正整数
returnr.test(obj);
}
functionbday(){
varbef=document.getElementById("bday").value;
if(isInteger(bef)){
varbvv=giveDateStr(getTargetday(-bef));
document.getElementById('ar').innerText=bvv;
}else{
alert("请输入正整数!");
document.getElementById("bday").value='';
document.getElementById("bday").focus();
}
}
functionaday(){
varatf=document.getElementById("aday").value;
if(isInteger(atf)){
varavv=giveDateStr(getTargetday(atf));
document.getElementById('ar').innerText=avv;
}else{
alert("请输入正整数!");
document.getElementById("aday").value='';
document.getElementById("aday").focus();
}
}
functiongetTargetday(num){
varnumber=null;
if(num==null||num==0){
number=0;
}else{
number=num;
}
var today=new Date();
var targetday_milliseconds=today.getTime()+1000*60*60*24*number;
var targetday=new Date();
targetday.setTime(targetday_milliseconds);//注意,这行是关键代码
returntargetday;
}
functiongiveDateStr(dd){
varriqiyue=dd.getMonth()+1;
varriqihao=dd.getDate();
varriqixingqi=null;
if(dd.getDay()=='0'){
xingqi="星期日";
}elseif(dd.getDay()=='1'){
xingqi='星期一';
}elseif(dd.getDay()=='2'){
xingqi='星期二';
}elseif(dd.getDay()=='3'){
xingqi='星期三';
}elseif(dd.getDay()=='4'){
xingqi='星期四';
}elseif(dd.getDay()=='5'){
xingqi='星期五';
}elseif(dd.getDay()=='6'){
xingqi='星期六';
}
varriqi=riqiyue+"月"+riqihao+"日"+"("+xingqi+")";
returnriqi;
}
</script>
</html>