uniapp日期区间选择器

uniapp日期区间选择器

在 uniapp 中创建一个简单的自定义日期范围的日期区间选择器:

  • 限制有效日期范围开始日期为 2024-01-01,结束日期为当日;

  • 默认日期区间为当日向前计算的7日区间;

  • 选择开始时间后,判断不可大于结束时间,且重置开始时间为结束时间;

  • 选择结束时间后,判断不可小于开始时间,且重置结束时间为开始时间;

示例代码:

html:

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:

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设置参数数据:

javascript 复制代码
data() {
  return {
    todayDate:'',
    startDate: '',
    endDate: '',
  }
},

created 或 onLoad 中,调用初始化日期区间方法:

javascript 复制代码
this.setInitTime();

methods 处理方法:

javascript 复制代码
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,'/'))
},
相关推荐
CodexDave1 天前
MySQL事务隔离级别与MVCC机制解析
前端·数据库·mysql·nginx·性能优化·负载均衡
Ai_easygo1 天前
AI Agent开发入门——从ReAct到Tool Calling,拆解Agent的底层运行逻辑
前端·人工智能·react.js
研☆香1 天前
分析制作html页面,如何划分页面结构
前端
kyriewen1 天前
我扒了最近的前端面经——2026年面试不背八股文了,考这5样
前端·面试·ai编程
IT_陈寒1 天前
Redis的持久化配置把我坑惨了:你以为数据安全了?
前端·人工智能·后端
小徐_23331 天前
uni-app 项目别再从零搭了!3 个 Wot UI 起手模板怎么选?
前端·uni-app
蜡台1 天前
uniapp pdf文件预览组件
pdf·uni-app·合同·pdfh5
张元清1 天前
React useResizeObserver Hook:追踪元素尺寸变化(2026)
javascript·react.js
赵庆明老师1 天前
Vben精讲:16-熟悉Vite前端工具链
前端
瑞瑞小同学1 天前
处理echarts x轴内容过多,重叠问题
前端·javascript·echarts