在系统当前时间的基础上,实现多种形式的日期计算,项目中经常要 计算当前时间 加多少天后的时间,找到三不错的方法,记录下来。
1.计算当前日期+N天后的日期
function CurrentDateAddDay(n){
var s, d, t, t2;
t = new Date().getTime();
t2 = n * 1000 * 3600 * 24;
t+= t2;
d = new Date(t);
s = d.getUTCFullYear() + "-";
s += ("00"+(d.getUTCMonth()+1)).slice(-2) + "-";
s += ("00"+d.getUTCDate()).slice(-2);
return s;
}
2.计算给定日期后的N天
function DateAddDay(str,n){
var dd, mm, yy;
var reg = /^(\d{4})-(\d{1,2})-(\d{1,2})$/;
if (arr = str.match(reg)) {
yy = Number(arr[1]);
mm = Number(arr[2])-1;
dd = Number(arr[3]);
} else {
var d = new Date();
yy = d.getUTCFullYear();
mm = ("00"+(d.getUTCMonth())).slice(-2);
dd = ("00"+d.getUTCDate()).slice(-2);
}
return date2str(yy, mm, dd,n);
}
3.计算给定日期后的N天
function SpecifiedDateAddDay(yy, mm, dd,n) {
var s, d, t, t2;
t = Date.UTC(yy, mm, dd);
t2 = n * 1000 * 3600 * 24;
t+= t2;
d = new Date(t);
s = d.getUTCFullYear() + "-";
s += ("00"+(d.getUTCMonth()+1)).slice(-2) + "-";
s += ("00"+d.getUTCDate()).slice(-2);
return s;
}
function culEndDate(){
var inputDate=document.all("rep_month_plan.start_date").value;
var datePartArray=inputDate.split('-');
//本月开始的第一天
var curFirstDay=new Date(datePartArray[0],datePartArray[1]-1);
//下月开始的第一天
var nextFirstDay=addDate('5','1',curFirstDay);
//下下月开始的第一天
var nnextFirstDay=addDate('5','2',curFirstDay);
//本月最后一天
var curEndDay= new Date(nextFirstDay.getTime()-1);
//下月最后一天
var nextEndDay= new Date(nnextFirstDay.getTime()-1);
alert(nextEndDay);
document.all("rep_month_plan.curEnddate").value=curEndDay.getYear() +'-' + (curEndDay.getMonth()+1) + '-' +curEndDay.getDate();
document.all("rep_month_plan.nextEnddate").value=nextEndDay.getYear() +'-' + (nextEndDay.getMonth()+1) + '-' +nextEndDay.getDate();
}
function addDate(type,NumDay,vdate){
var date=new Date(vdate);
type = parseInt(type) //类型
var lIntval = parseInt(NumDay)//间隔
switch(type){
case 6 ://年
date.setYear(date.getYear() + lIntval)
break;
case 7 ://季度
date.setMonth(date.getMonth() + (lIntval * 3) )
break;
case 5 ://月
date.setMonth(date.getMonth() + lIntval)
break;
case 4 ://天
date.setDate(date.getDate() + lIntval)
break
case 3 ://时
date.setHours(date.getHours() + lIntval)
break
case 2 ://分
date.setMinutes(date.getMinutes() + lIntval)
break
case 1 ://秒
date.setSeconds(date.getSeconds() + lIntval)
break;
default:
}