示例:选择时间段,自动计算出请假天数。
项目要求是,只要请假,最低请假单位是0.5天,时间一旦超过中午12点,天数加0.5天
changeTime(e) {
if (e.length > 0) {
console.log(e)
let day1 = e[0].split(' ')[0]
let day2 = e[1].split(' ')[0]
// console.log(day1)
let time1 = new Date(day1 + ' 12:00:00')
let time2 = new Date(day2 + ' 12:00:00')
console.log(new Date(e[0]), '请假开始时间')
console.log(new Date(e[1]), '请假结束时间')
console.log(time1, '请假开始那天中午12点')
console.log(time2, '请假结束那天中午12点')
console.log(new Date(e[0]) > time1, '开始时间是否超过中午12点')
console.log(new Date(e[1]) > time2, '结束时间是否超过中午12点')
let computerDay = (new Date(day2) - new Date(day1)) / 1000 / 60 / 60 / 24
// console.log(computerDay, '结束时间是否超过开始的日期')
this.model1.formData.leaveDays = computerDay - 0
if (new Date(e[0]) > time1) {
this.model1.formData.leaveDays += 0
} else {
this.model1.formData.leaveDays += 0.5
}
if (new Date(e[1]) > time2) {
this.model1.formData.leaveDays += 0.5
} else {
this.model1.formData.leaveDays += 0
}
this.model1.formData.time = e
this.model1.formData.startTime = e[0]
this.model1.formData.endTime = e[1]
this.$refs.uForm.validateField('formData.time')
}
},
思路:
该项目是用的uniapp的日期时间选择器的范围用法,在选择时间和日期之后,会返回一个包含年月日时分秒的数组,['2024-01-24 20:10:46', '2024-01-25 20:10:46']
分别截取起止时间的年月日,获取开始时间的中午12点和结束时间的中午12点,
2024-01-24 12:00:00 2024-01-25 12:00:00
用结束时间的年月日减去开始时间的年月日,再换算成天数,就是基本天数,基本天数再判断是否需要加上下面的判断天数,
(new Date(2024-01-25) - new Date(2024-01-24)) / 1000 / 60 /60 / 24
将开始时间与当天的中午12点进行比较,若晚于12点,则请假天数不用加,若早于12点,则请假时间加上0.5,
如果请假的开始时间晚于中午12点,结束时间仍然是当天的话,那结束时间一定会晚于中午12点,
将结束时间与当天的中午12点进行比较,若晚于12点,则请假天数加0.5,若早于12点,则请假时间不用加
比如 请假从今天上午开始到明天上午,则请假时间为1.5天
(该代码只使用于本项目的需求,若有其他复杂的需求,可以参考思路进行修改)