1.主方法入口,其中获得今天日期方法在下面一个代码块
getIsExpire = () => {
const endDt = 20210807; //结束时间格式
let day1 = new Date(this.getToDay()); //获取今天的日期
//将结束时间yyyyMMdd转换为yyyy-MM-dd格式
let day2 = new Date(endDt.slice(0,4) + "-" + endDt.slice(4,6) + "-" + endDt.slice(6,8));
//计算相差几天 1000毫秒 = 1秒 60秒 = 1分 60分 = 1h 24 小时 = 1天
const distanceTime = (day2 - day1) / (1000 * 60 * 60 * 24);
//由于是在react 格式写在一周内的判断,所以是用原生还是vue自己转换一下
if( distanceTime <= 7 ){
this.setState({
isExpire: true,
});
}else{
this.setState({
isExpire: false,
});
}
}
2.获得当前日期方法(yyyy-MM-dd格式)
getToDay() {
//生成今天的时间
let now = new Date();
//获得年份 例如 2021
let nowYear = now.getFullYear();
//获得月份
let nowMonth = now.getMonth();
//获得今天日期
let nowDate = now.getDate();
//这一步好像没必要
let newdate = null;
//这一步好像也没必要,但为了不报错,就先放在这
newdate = new Date(nowYear, nowMonth, nowDate);
//调用doHandleMonth判断当前字符是不是小于10,如果小于10,需要给前面加上一个0,例如07
//这个月份+1是因为我们月份是从0开始的也就是6月份得到的是5所以需要+1
nowMonth = this.doHandleMonth(nowMonth + 1);
//日期和月份一样需要判断是否小于10
nowDate = this.doHandleMonth(nowDate);
//字符串拼接
return nowYear + "-" + nowMonth + "-" + nowDate;
}
3.判断月份或日期是否小于10
doHandleMonth(month) {
if (month.toString().length === 1) {
month = "0" + month;
}
return month;
}