js选中起始时间使用标准时间毫秒值计算一年后的当前少一天的日期
实际代码里面带入默认日期’20230301’这个特殊日期,因为下一年的当前日期少一天为闰年的2月会有29天,使用特殊值校验代码效果图
HTML部分代码
<el-button @click="chengTime()" type="warning">按钮一</el-button>
<el-button @click="chengTimes()" type="info">按钮二</el-button>
JS部分代码
dateFormat(val){
let date=new Date(val);
let y=date.getFullYear();
let m=date.getMonth()+1;
m=m<10?'0'+m:m;
let d=date.getDate();
d=d<10?'0'+d:d;
let time=y+'-'+m+'-'+d;
return time
},
chengTime(){
let timeList=[]
let nowtime='20230301'
let nowyear=Number(nowtime.substring(0,4))+1
let nowmonth=nowtime.substring(4,6)
let nowday=nowtime.substring(6,8)
if(nowmonth=='02'&&nowday=='29'){
nowmonth='03';
nowday='01'
}
timeList.push((nowyear+''));
timeList.push(nowmonth);
timeList.push(nowday);
let timeStr=timeList[0]+'-'+timeList[1]+'-'+timeList[2]
let oldtime=new Date(timeStr).getTime()-3600*24*1000
let formattedTime=this.dateFormat(oldtime).replace("-", "").replace("-", "")
this.$message({
message: `按钮一的值,${formattedTime}`,
type: 'success'
})
},
chengTimes(){
let nowtime='20230301'
let nowyear=Number(nowtime.substring(0,4))+1;
let nowmonth=parseInt(nowtime.substring(4,6))-1;
let nowday=parseInt(nowtime.substring(6,8))-1;
let formattedTime=this.dateFormat(new Date(nowyear,nowmonth,nowday)).replace("-", "").replace("-", "")
this.$message({
message: `按钮二的值,${formattedTime}`,
type: 'error'
})
}
需要注意的是:方法一在实际使用中需要考虑浏览器对于原生JS的支持版本,我在实际使用中发现低版本的好像不兼容。使用方法二的话就兼容性更好,更推荐使用方法二去获取下一年当前日期少一天的日期数据。