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,'/'))
},
相关推荐
渣哥13 小时前
Spring Boot 本质揭秘:约定优于配置 + 自动装配
javascript·后端·面试
颜酱13 小时前
了解 pnpm 的优势,然后将已有项目的 yarn 换成 pnpm
前端·javascript·前端工程化
海在掘金6112713 小时前
从"鬼知道这对象有啥"到"一目了然" - TS接口的实战魔力
前端
spionbo13 小时前
Vue 模拟键盘组件封装方法与使用技巧详解
前端
泉城老铁13 小时前
springboot 对接发送钉钉消息,消息内容带图片
前端·spring boot·后端
顾青13 小时前
微信小程序 VisionKit 实战(二):静态图片人脸检测与人像区域提取
前端·微信小程序
hmfy13 小时前
那些前端老鸟才知道的秘密
前端
野葳蕤13 小时前
react总览
前端
不一样的少年_13 小时前
她说想要浪漫,我把浏览器鼠标换成了柴犬,点一下就有烟花(附源码)
前端·javascript·浏览器
顾青13 小时前
微信小程序实现身份证识别与裁剪(基于 VisionKit)
前端·微信小程序