uniapp日期区间选择器
在 uniapp 中创建一个简单的自定义日期范围的日期区间选择器:
- 限制有效日期范围开始日期为 2024-01-01,结束日期为当日;
- 默认日期区间为当日向前计算的7日区间;
- 选择开始时间后,判断不可大于结束时间,且重置开始时间为结束时间;
- 选择结束时间后,判断不可小于开始时间,且重置结束时间为开始时间;
示例代码:
html:
<view class="picker-container">
<view class="picker-item">
<view class="picker-item-title">开始日期 :</view>
<picker mode="date" :value="startDate" start="2024-01-01" :end="todayDate" @change="bindStartDateChange">
<view>{{startDate}}</view>
</picker>
</view>
<view class="picker-item">
<view class="picker-item-title">结束日期 :</view>
<picker mode="date" :value="endDate" start="2024-01-01" :end="todayDate" @change="bindEndDateChange">
<view>{{endDate}}</view>
</picker>
</view>
</view>
CSS:
.picker-container{ height: 80rpx; font-size: 26rpx; display: flex; justify-content: space-around; align-items: center; border-radius: 10rpx; background-color: #fff;}
.picker-item{ padding: 16rpx; display: flex; justify-content: space-around; align-items: center;}
.picker-item-title{ color: #999; white-space: nowrap;}
.picker-item picker{ flex: 1; color: #8B4F8E; font-weight: bold;}
data设置参数数据:
data() {
return {
todayDate:'',
startDate: '',
endDate: '',
}
},
created 或 onLoad 中,调用初始化日期区间方法:
this.setInitTime();
methods 处理方法:
setNum(num){
if(num < 10){
return '0' + num;
}else{
return num;
}
},
setInitTime(){
let thisTime = new Date();
this.todayDate = thisTime.getFullYear() + '-' + this.setNum(thisTime.getMonth() + 1) + '-' + this.setNum(thisTime.getDate());
let startTime = new Date(thisTime - (24 * 60 * 60 * 1000 * 6));
this.startDate = startTime.getFullYear() + '-' + this.setNum(startTime.getMonth() + 1) + '-' + this.setNum(startTime.getDate());
this.endDate = this.todayDate;
this.getData();
},
bindStartDateChange(e) {
if(new Date(e.detail.value) > new Date(this.endDate)){
// 开始时间不可大于结束时间
this.startDate = this.endDate;
}else{
this.startDate = e.detail.value;
}
this.getData();
},
bindEndDateChange(e) {
if(new Date(e.detail.value) < new Date(this.startDate)){
// 结束时间不可小于开始时间
this.endDate = this.startDate;
}else{
this.endDate = e.detail.value;
}
this.getData();
},
getData(){
// 获取对应时间段数据
console.log(this.startDate.replace(/-/g,'/') + '-' + this.endDate.replace(/-/g,'/'))
},