问题描述:
使用了layui的时间控件(laydate)并设置了默认值,除了默认值无法清空外,其他功能使用正常。
function getNowFormatDate() {
var DateTime = new Date(), currentDate, sevenDayDate;
currentDate = DateTime.toLocaleString().replace(/\//g, '-');
DateTime.setDate(DateTime.getDate() - 7);
sevenDayDate = DateTime.toLocaleString().replace(/\//g, '-');
return sevenDayDate + ' - ' + currentDate;
}
var DayDate = getNowFormatDate();
laydate.render({
elem: '#DateTime',
range: true,
type: 'datetime',
value: DayDate,
max: DayDate.split(' - ')[1].trim()
});
在网上也找了问题的解决方案:
使用回调函数done清空时间筛选器的值
laydate.render({
elem: '#DateTime',
range: true,
type: 'datetime',
value: DayDate,
max: DayDate.split(' - ')[1].trim(),
done: function (value, date) {
this.value = value;
this.elem.val(value);
}
});
虽然解决了该问题,但我任然存在疑惑,因为我查找了项目中其他使用laydate控件的地方,它们虽然页设置了默认值,但并不存在时间无法清空问题。
最终通过比对设置的默认值格式发现是控件使用的默认时间格式为 yyyy-MM-dd HH:mm:ss,而我设置的值的是 2025-2-14 10:56:57 - 2025-2-21 10:56:57 很显然不符合该格式,最终导致时间筛选器无法清空。最终解决方案是修改控件的时间格式为 y-M-d H:m:s 允许每一个值不补0,当然你也可以选择对时间进行格式化进行补0操作。
laydate.render({
elem: '#DateTime',
range: true,
type: 'datetime',
format: 'y-M-d H:m:s',
value: DayDate,
max: DayDate.split(' - ')[1].trim(),
});
// 格式化日期时间函数
function formatDateTime(dateObj) {
const date = new Date(date);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}