前言
项目中需要判断两个日期之间间隔的(月数、周数、天数、),所以在此分享一下
目录
一、 两个时间相差月数
二、 两个时间相差周数
三、 两个时间相差天数
四、 其他
正文
一、 两个时间相差月数
1. 代码
function disMonthF(dateList){
let disMonth=0
let disYear=dateList[1].getFullYear()-dateList[0].getFullYear();
let preDisMonth=disYear*12
let endDateMMonth=dateList[1].getMonth();
let startDateMMonth=dateList[0].getMonth();
if(startDateMMonth<endDateMMonth){
disMonth=preDisMonth+(12+endDateMMonth-startDateMMonth);
}else{
disMonth=preDisMonth+(endDateMMonth-startDateMMonth);
}
return disMonth;
}
//测试数据,记得创建date 对象
let date0=new Date(1591690485000);
let date1=new Date(1623226485496);
disMonthF([date0,date1]);
2. 运行结果
二、 两个时间相差周数
1. 代码
function disWeekF(dateList) {
//这里的date1,date2都是Date对象
var dt1 = dateList[1];
var dt2 = dateList[0];
//向上取整
return Math.ceil(Math.abs(dt1 - dt2) / 1000 / 60 / 60 / 24 / 7);
}
//测试数据,记得创建date 对象
let date0=new Date(1591690485000);
let date1=new Date(1623226485496);
disWeekF([date0,date1]);
2. 运行结果
三、 两个时间相差天数
1. 代码
function disDayF(dateList) {
let days=(dateList[1] - dateList[0])/(1*24*60*60*1000);
//这里做了向上取整,当然如果你需要的话也可以进行向下取整 即 Math.floor()
return Math.ceil(days);
}
//测试数据,记得创建date 对象
let date0=new Date(1591690485000);
let date1=new Date(1623226485496);
disDayF([date0,date1]);
2. 运行结果
四、其他
1. 获取上个年/月/ 的 月/日
有点绕口,获取之前的“ 某个年/月/日,比如你的需求中获取去年的几月份,或者上个月的某号。
var fdate = new Date()
,fyears = fdate.getFullYear()
,fmoths = fdate.getMonth()
,fdate_sgy=new Date(fyears , fmoths-1 , fdate.getDate())//上个月data
,fyear_sgy=fdate_sgy.getFullYear()//上个月_年
,fmonth_sgy=(fdate_sgy.getMonth()+1)<10?"0"+(fdate_sgy.getMonth()+1) : (fdate_sgy.getMonth()+1)//上个月_月
,fday_sgy=fdate_sgy.getDate()<10?"0"+fdate_sgy.getDate() : fdate_sgy.getDate()//上个月_天
2. 获取当年的1月1号
同理,如果要获得当月的1号,就 date.getMonth()+1
function get0101(){
var date= new Date();
var year= date.getFullYear();
//var month=date.getMonth();
//console.log(month+1); //当月的月份
var first0101 = year + '-' + '01' + '-' + '01';
return first0101;
}
get0101();
3. 获取当前30天之前的日期
注释中的30 可以改为其他想要的天数
function getOldDate(){
//获取当前时间
let myDate = new Date();
let arr = myDate.toLocaleDateString();
//获取三十天前日期
let lw = new Date(myDate - 1000 * 60 * 60 * 24 * 30);//最后一个数字30可改,30天的意思
let lastY = lw.getFullYear();
let lastM = lw.getMonth()+1;
let lastD = lw.getDate();
let startdate=lastY+"-"+(lastM<10 ? "0" + lastM : lastM)+"-"+(lastD<10 ? "0"+ lastD : lastD);//三十天之前日期
return startdate;
}
getOldDate();