微信小程序 自定义时间组件

2022/8/23 1:54:04

本文主要是介绍微信小程序 自定义时间组件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

效果图

效果

代码

xml

<view class="date_bg_view">
</view>
<view class="date_content">
  <view class="date_title">
    <van-icon name="cross" class="close" size="20px" color="#999999" bindtap="onClose"/>
    <text class="date_title_txt">选择时间</text>
  </view>
  <view class="line"></view>
  <!-- 快速选择 -->
  <view class="date_quick_choose">
    <text class="date_quick_txt">快速选择</text>
    <view class="date_quick_show">
      <view class="quick_cell_flag" wx:for="{{dateList}}" wx:key="id" bindtap="handleQuickChoose" data-item="{{item}}" wx:if="{{item.flag}}">
        {{item.value}}
      </view>
      <view class="quick_cell" wx:for="{{dateList}}" wx:key="id" bindtap="handleQuickChoose" data-item="{{item}}" wx:if="{{!item.flag}}">
        {{item.value}}
      </view>
    </view>
  </view>
  <!-- 自定义时间 -->
  <view class="date_quick_choose">
    <text class="date_quick_txt">自定义时间</text>
    <view class="date_picker">
      <picker mode="date" value="{{startDate}}" start="2015-09-01" end="2999-12-31" bindchange="bindDateChange" data-type="1"  mask-style=" color='#0A3E79'">
        <view class="picker">
        {{startDate?startDate:'开始时间'}}
        </view>
      </picker> 
      <text style="width: 20rpx;height: 1rpx;background-color: #999999;"></text>
      <picker mode="date" value="{{endDate}}" start="2015-09-01" end="2999-12-31" bindchange="bindDateChange"  data-type="2">
        <view class="picker">
          {{endDate?endDate:'结束时间'}}
        </view>
      </picker>
    </view>
  </view>
  <button class="sure_btn" bindtap="handleSure"> 确定 </button>
</view>

wxss

.date_bg_view{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #000000;
  opacity: 0.3;
  z-index: 10;
}
.date_content{
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  background-color: #ffffff;
  height: 65%;
  bottom: 0;
  position: fixed;
  left: 0;
  width: 100%;
  z-index: 11;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
}
.date_title{
  z-index: 11;
  width: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  height: 90rpx;
}
.close{
  width: 10%;
  margin: 10rpx;
}
.date_title_txt{
  margin-left: 30%;
  align-self: center;
  font-size: 35rpx;
  font-weight: bold;
  font-family: SourceHanSansCN-Medium;
}
.line{
  width: 100%;
  margin: 10rpx;
  height: 1rpx;
  background-color: #EEEEEE;
}
.date_quick_choose{
  z-index: 11;
  width: 100%;
  padding: 20rpx;
}
.date_quick_txt{
  font-family: SourceHanSansCN-Medium;
  margin: 20rpx;
  font-size: 30rpx;
  color: #666666;
  z-index: 12;
}
.date_quick_show{
  width: 100%;
  flex-wrap: wrap;
  display: flex;
  justify-content: flex-start;
  flex-direction: row;
  align-items: center;
  z-index: 12;
}
.quick_cell{
  padding: 5rpx;
  width: 29%;
  margin: 2%;
  font-size: 30rpx;
  text-align: center;
  z-index: 12;
  height: 60rpx;
  background-color: #F7F7F7;
  color: #999999;
  border-radius: 10rpx;
  font-family: SourceHanSansCN-Medium;
  border: 1rpx solid #999999;
}
.quick_cell_flag{
  padding: 5rpx;
  width: 29%;
  margin: 2%;
  font-size: 30rpx;
  text-align: center;
  z-index: 12;
  height: 60rpx;
  background-color: #FFFFFF;
  color: #0A3E79;
  border-radius: 10rpx;
  font-family: SourceHanSansCN-Medium;
  border: 1rpx solid #0A3E79;
}
.date_picker{
  display: flex;
  width: 80%;
  margin-left: 10%;
  justify-content: space-between;
  align-items: center;
  margin-top: 30rpx;
}
.picker{
  font-size: 30rpx;
  border: 1rpx solid #0A3E79;
  padding: 10rpx 40rpx;
  background-color: #FFFFFF;
  color: #0A3E79;
  font-weight: bold;
}
.sure_btn{
  background-color: #0A3E79;
  color: #ffffff;
  font-size: 105%;
  width: 90%;
  margin-top: 90rpx;
  text-align: center;
  height: 80rpx;
}

js

import { formatDate,getTimeLastWeek,getTimeLastMonth,getTimeThreeMonth,getTimeHalfYear } from "../../utils/util";
const app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    dateList: [{
        id: 1,
        value: '当天',
        flag: false
      },
      {
        id: 2,
        value: '近七天',
        flag: false
      },
      {
        id: 3,
        value: '近一个月',
        flag: false
      },
      {
        id: 4,
        value: '近三个月',
        flag: false
      },
      {
        id: 5,
        value: '近半年',
        flag: false
      }
    ],
    startDate: '',
    endDate: '',
    currentTime:formatDate(new Date()),
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 快速选择
     * @param {*} e 
     */
    handleQuickChoose(e) {
      let that = this;
      let item1 = e.currentTarget.dataset.item;
      that.data.dateList.forEach(item => {
        if (item.id === item1.id) {
          item.flag = true;
        } else {
          item.flag = false;
        }
      })
      that.setData({
        dateList: that.data.dateList
      })

      switch (item1.id) {
        case 1: //当天
          console.log(1,that.data.currentTime);
          that.setData({
            startDate:that.data.currentTime,
            endDate:that.data.currentTime
          })
          break;
        case 2: //近七天
          console.log(2);
          that.setData({
            startDate:getTimeLastWeek(new Date()),
            endDate:that.data.currentTime
          })
          break;
        case 3: //近一个月
          console.log(3);
          that.setData({
            startDate:getTimeLastMonth(new Date()),
            endDate:that.data.currentTime
          })
          break;
        case 4: //近三个月
          console.log(4);
          that.setData({
            startDate:getTimeThreeMonth(new Date()),
            endDate:that.data.currentTime
          })
          break;
        case 5: //近半年
          console.log(5);
          that.setData({
            startDate:getTimeHalfYear(new Date()),
            endDate:that.data.currentTime
          })
          break;
      }
      console.log(that.data.dateList);
      // console.log(e);
    },
    /**
     * 选择时间
     */
    bindDateChange(e) {
      console.log('picker发送选择改变,携带值为', e)
      let that = this;
      let type = e.currentTarget.dataset.type
      if (type == 1) {
        that.setData({
          startDate: e.detail.value
        })
      } else {
        that.setData({
          endDate: e.detail.value
        })
      }
    },
    /**
     * 顶部关闭按钮
     */
    onClose() {
      this.triggerEvent('sync', {
        show: false
      })
    },

    /**
     * 确定
     */
    handleSure() {
      let that = this;
      if(!that.data.startDate){
        app.myShowToast('开始时间不能为空');
        return false;
      }
      if(!that.data.endDate){
        app.myShowToast('结束时间不能为空');
        return false;
      }
      if(that.data.startDate <= that.data.endDate){
        that.triggerEvent('sync', {
          show: false,
          startDate: that.data.startDate,
          endDate: that.data.endDate
        })
      }else{
        app.myShowToast('结束时间不能小于开始时间');
        return false;
      }
    
    }
  },

})

工具类 不一定运算正确,有更好的可以继续实验 三个月 以及半年还未测试多种突发情况

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}


/**
 * 当天
 * @param {*} date 
 */
const formatDate = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return [year, month, day].map(formatNumber).join('-')  
}

/** 
* 时间戳转化为年 月 日 时 分 秒 
* number: 传入时间戳 
* format:返回格式,支持自定义,但参数必须与formateArr里保持一致 
*/
function formatTimeTwo(number, format) {
 
  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr = [];
 
  var date = new Date(number * 1000);
  returnArr.push(date.getFullYear());
  returnArr.push(formatNumber(date.getMonth() + 1));
  returnArr.push(formatNumber(date.getDate()));
 
  returnArr.push(formatNumber(date.getHours()));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));
 
  for (var i in returnArr) {
      format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
}
 
/**
 * 近七天
 * @param {*} last 
 */
const getTimeLastWeek = last => {
  const year = last.getFullYear()
  const day = last.getDate()
  const ti = day - 7
  // 判断是否月初
  if (ti <= 0) {
    const month = last.getMonth() + 1 - 1
    const d = new Date(year, month, 0)
    const dayBig = d.getDate() //获取当月的所有天数
    const ti1 = dayBig + ti
    return [year, month, ti1].map(formatNumber).join('-')
  } else {
    const month = last.getMonth() + 1
    return [year, month, ti].map(formatNumber).join('-')
  }
  // return [year, month, day].map(formatNumber).join('-')

}

/**
 * 近1个月
 * @param {*} last 
 */
const getTimeLastMonth = last => {
  const year = last.getFullYear()
  const day = last.getDate()
  const ti = day - 30 
  // 判断是否月初
  if (ti <= 0) {
    const month = last.getMonth() + 1 - 1
    const d = new Date(year, month, 0)
    const dayBig = d.getDate() //获取当月的所有天数
    const ti1 = dayBig + ti
    return [year, month, ti1].map(formatNumber).join('-')
  } else {
    const month = last.getMonth() + 1
    return [year, month, ti].map(formatNumber).join('-')
  }
}

/**
 * 近3个月
 * @param {*} last 
 */
const getTimeThreeMonth = last => {
  const year = last.getFullYear()
  const month = last.getMonth() + 1
  const day = last.getDate()
  // 判断三个月的开始月份
  const startMonth = month - 3;
  // 判断是否是年初
  if(startMonth <= 0){
    year = year - 1 ;
  }
  return [year, startMonth, day].map(formatNumber).join('-')
}

/**
 * 近3个月
 * @param {*} last 
 */
const getTimeHalfYear = last => {
  const year = last.getFullYear()
  const month = last.getMonth() + 1
  const day = last.getDate()
  // 判断三个月的开始月份
  const startMonth = month - 6;
  // 判断是否是年初
  if(startMonth <= 0){
    year = year - 1 ;
  }
  return [year, startMonth, day].map(formatNumber).join('-')
}

/**
 * 赋0
 * @param {*} n 
 */
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

module.exports = {
  formatTime: formatTime,
  formatDate:formatDate,
  formatTimeTwo: formatTimeTwo,
  getTimeLastWeek:getTimeLastWeek,
  getTimeLastMonth:getTimeLastMonth,
  getTimeThreeMonth:getTimeThreeMonth,
  getTimeHalfYear:getTimeHalfYear
}

父视图

引入组件

## 引入
"datePicker":"../../../components/datePicker/index"

应用

<!-- 时间选择组件 bind:sync 子类回传数据的方法-->
<datePicker wx:if="{{show}}" bind:sync="syncGetDate"></datePicker>

js

 syncGetDate(e){
  let that = this;
  let show = e.detail.show; 
  if(!show){ // 子组件点击了关闭   关闭弹窗
    that.setData({
      show:false
    })
  }
  console.log("子组件:",e);
  // that.getPurchaseList();
}

子组件



这篇关于微信小程序 自定义时间组件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程