1.日期选择器
<a-form-model-item label="计租期" prop="Dates" :rules="{ required: true, message: '请输入计租期',trigger: 'blur',}">
<a-range-picker style="width:300px;" v-model='form.Dates' :disabled='see' @change="changeDate" />
</a-form-model-item>
2.定义开始时间和结束时间
startTime: null,
endTime: null
3.组件日期选择器的改变事件
这里用到的组件是ant-design-vue,当选择完日期后触发,调用写的计算日期选择器的方法,输出结果
changeDate(times, e) {
console.log(e)
this.startTime = e[0]
this.endTime = e[1]
this.monthDayDiff()
},
4. 计算时间差的方法
monthDayDiff() {
// this指针
let _this = this;
let flag = [1, 3, 5, 7, 8, 10, 12, 4, 6, 9, 11, 2];
let start = new Date(_this.startTime);
let end = new Date(_this.endTime);
let year = end.getFullYear() - start.getFullYear();
let month = end.getMonth() - start.getMonth();
let day = end.getDate() - start.getDate();
if (month < 0) {
year--;
month = end.getMonth() + (12 - start.getMonth());
}
if (day < 0) {
month--;
let index = flag.findIndex((temp) => {
return temp === start.getMonth() + 1
});
let monthLength;
if (index <= 6) {
monthLength = 31;
} else if (index > 6 && index <= 10) {
monthLength = 30;
} else {
monthLength = 28;
}
day = end.getDate() + (monthLength - start.getDate());
}
this.result = `相差${year}年${month}月${day}天`;
console.log(this.result)
},