js 获取前后多少天(小时,分,秒)
程序员文章站
2024-01-28 09:21:40
...
js Date
时间相关链接
获取前后多少天(小时,分,秒)
// 获取前后多少天(小时,分,秒)
function GetDate_ab(time_ab,str) {
var dd = new Date(str);
dd.setDate(dd.getDate()+time_ab);//前后time_ab天(time_ab可为负数)
//dd.setHours(dd.getHours()+time_ab);//前后time_ab小时(time_ab可为负数)
//dd.setMinutes(dd.getMinutes()+time_ab);//前后time_ab分(time_ab可为负数)
//dd.setSeconds(dd.getSeconds()+time_ab);//前后time_ab秒(time_ab可为负数)
var y = dd.getFullYear();
var m = (dd.getMonth()+1)<10?"0"+(dd.getMonth()+1):(dd.getMonth()+1);//获取月份,不足10补0
var d = dd.getDate()<10?"0"+dd.getDate():dd.getDate();//获取日期,不足10补0
var hh = dd.getHours()<10?"0"+dd.getHours():dd.getHours();//获取小时,不足10补0
var mm = dd.getMinutes()<10?"0"+dd.getMinutes():dd.getMinutes();//获取分,不足10补0
var ss = dd.getSeconds()<10?"0"+dd.getSeconds():dd.getSeconds();//获取秒,不足10补0
return y+"-"+m+"-"+d+" "+hh+":"+mm+":"+ss;
}
console.log("昨天:"+GetDate_ab(-1,''));
console.log("今天:"+GetDate_ab(0,''));
console.log("明天:"+GetDate_ab(1,''));
console.log("后天:"+GetDate_ab(2,''));
获取本周第一天
var now = new Date();
var week_n = now.getDay(); // 3, 表示星期三,1234560
console.log(GetDate_ab(1-week_n,''),1-week_n);
获取本周最后一天
var now = new Date();
var week_n = now.getDay(); // 3, 表示星期三,1234560
console.log(GetDate_ab(7-week_n,''),7-week_n);
获取某月第一天,最后一天
var now = new Date('2019-9-10');
var y = now.getFullYear();
var m = now.getMonth();
var d = now.getDate();
//获取本月第一天
console.log(GetDate_ab(1-d,''));
//获取本月最后一天
var mm=0;
if(m<=9){
mm=m+2;
}else if(m==10){
mm=12;
y=y+1;
}else if(m==11){
mm=1;
y=y+1;
}
console.log(GetDate_ab(-1,y+'-'+mm+'-01'));