微信小程序之时间选择器(包含年,月,日。时,分,秒)自定义组件

一、建立组件
/components/timePicker/index在这里插入图片描述
index.js

// components/timePicker/index.js
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        /**
         * 组件类型 date:日期(yyyy-MM-dd) time:时间(hh:mm:ss) dateTime: 日期时间(yyyy-MM-dd hh:mm:ss)
         */
        mode: {
            type: String,
            value: 'date',
            observer: 'modeChange'
        },
        disabled: {
            type: Boolean,
            value: false
        },
        placeholder: String
    },

    /**
     * 组件的初始数据
     */
    data: {
        pickerArray: [], //日期控件数据list
        pickerIndex: [], //日期控件选择的index
        dateString: '' //页面显示日期
    },

    /**
     * 组件的方法列表
     */
    methods: {

        modeChange: function (newVal, oldVal) {
            this.getPickerArray(newVal)
        },
        //补零
        formatNumber(n) {
            n = n.toString()
            return n[1] ? n : '0' + n
        },
        //日期时间格式化
        formateDateTime(arr) {
            let mode = this.data.mode
            switch (mode) {
                case 'date':
                    return arr.map(this.formatNumber).join('-')
                    break;
                case 'time':
                    return arr.map(this.formatNumber).join(':')
                    break;

                case 'dateTime':
                    return arr.slice(0, 3).map(this.formatNumber).join('-') + ' ' + arr.slice(3, 6).map(this.formatNumber).join(':')
                    break;
            }
        },

        /**
         *
         * 获取本月天数
         * @param {number} year
         * @param {number} month
         * @param {number} [day=0] 0为本月0最后一天的
         * @returns number 1-31
         */
        _getNumOfDays(year, month, day = 0) {
            return new Date(year, month, day).getDate();
        },

        //获取pickerArray
        getPickerArray(mode = this.data.mode) {
            let date = new Date();
            let pickerArray = []
            //年
            let year = [];
            for (let i = date.getFullYear() - 5; i <= date.getFullYear() + 5; i++) {
                year.push({
                    id: i,
                    name: i + '年'
                });
            }
            let currentYear = date.getFullYear();
            let yearIndex = year.findIndex(item => item.id == currentYear);
            pickerArray.push({
                picker: 'year',
                value: year,
                pickerIndex: yearIndex
            })
            //月
            let month = [];
            for (let i = 1; i <= 12; i++) {
                month.push({
                    id: i,
                    name: i + '月'
                });
            }
            pickerArray.push({
                picker: 'month',
                value: month,
                pickerIndex: date.getMonth(),
            })
            //日
            let dayNum = this._getNumOfDays(date.getFullYear(), date.getMonth() + 1);
            let day = [];
            for (let i = 1; i <= dayNum; i++) {
                day.push({
                    id: i,
                    name: i + '日'
                });
            }
            pickerArray.push({
                picker: 'day',
                value: day,
                pickerIndex: date.getDate() - 1,
            })
            //时
            let time = [];
            for (let i = 0; i <= 23; i++) {
                time.push({
                    id: i,
                    name: this.formatNumber(i)
                });
            }
            pickerArray.push({
                picker: 'time',
                value: time,
                pickerIndex: date.getHours(),
            })
            //分
            let minutes = [];
            for (let i = 0; i <= 59; i++) {
                minutes.push({
                    id: i,
                    name: this.formatNumber(i)
                });
            }
            pickerArray.push({
                picker: 'minutes',
                value: minutes,
                pickerIndex: date.getMinutes(),
            })
            //秒
            let seconds = [];
            for (let i = 0; i <= 59; i++) {
                seconds.push({
                    id: i,
                    name: this.formatNumber(i)
                });
            }
            pickerArray.push({
                picker: 'seconds',
                value: seconds,
                pickerIndex: date.getSeconds(),
            })

            let pickerIndex = []
            //过滤不同mode的pickerArray keys
            let formatPickerArray = () => {
                switch (mode) {
                    case 'date':
                        return ['year', 'month', 'day']
                        break;
                    case 'dateTime':
                        return ['year', 'month', 'day', 'time', 'minutes', 'seconds']
                        break;
                    case 'time':
                        return ['time', 'minutes', 'seconds']
                        break;
                }
            }
            //过滤不同mode的pickerArray values
            let pickerValues = formatPickerArray(mode)
            let formatPickers = []
            // pickerArray.filter(item =>
            //     pickerValues.indexOf(item.picker) >= 0
            // )
            //获取pickers选项和默认选择下标
            pickerArray.map(item => {
                if (pickerValues.indexOf(item.picker) >= 0) {
                    pickerIndex.push(item.pickerIndex)
                    formatPickers.push(item.value)
                }
            })
            this.setData({
                pickerArray: formatPickers,
                pickerIndex
            })
            //通过下标获取对应时间
            let currentDate = this.getPickerValue(pickerIndex)
            this.setData({
                dateString: currentDate
            })

        },

        getPickerValue(pickerIndex) {
            let date = this.data.pickerArray.map((item, index) =>
                // console.log(this.data.pickerArray[index][pickerIndex[index]].id, pickerIndex)
                this.data.pickerArray[index][pickerIndex[index]].id
            )
            let dateString = this.formateDateTime(date)

            return dateString
        },
        pickerChange: function (e) {
            let currentDate = this.getPickerValue(e.detail.value)
            this.setData({
                dateString: currentDate
            })
            let detail = {
                value: currentDate
            }
            this.triggerEvent('onPickerChange', detail);
        },
        //月变化时获取当月多少天
        pickerColumnChange: function (e) {
            let value = e.detail
            let year = this.data.pickerArray[0][this.data.pickerIndex[0]].id
            if (this.data.mode !== 'time') {
                if (value.column === 1) {
                    let days = this._getNumOfDays(year, value.value + 1)
                    let day = [];
                    for (let i = 1; i <= days; i++) {
                        day.push({
                            id: i,
                            name: i + '日'
                        });
                    }
                    this.data.pickerArray[2] = day
                    this.setData({
                        pickerArray: this.data.pickerArray
                    })
                }
            }
        },
        pickerCancel: function (e) {}

    },

    lifetimes: {
        attached() {
            // 在组件实例进入页面节点树时执行
        },
        detached() {
            // 在组件实例被从页面节点树移除时执行
        },
        ready() {
            this.getPickerArray()
        }
    }
});

index.json

{
  "component": true,
  "usingComponents": {}
}

index.wxml

<!-- components/timePicker/index.wxml -->
<view>
  <picker disabled="{{disabled}}" mode="multiSelector" bindchange="pickerChange" bindcolumnchange="pickerColumnChange"
    bindcancel="pickerCancel" value="{{pickerIndex}}" range="{{pickerArray}}" range-key="{{'name'}}">
    <view>
      <input placeholder="{{placeholder}}" class="weui-input" disabled="{{true}}" value="{{dateString}}"></input>
    </view>
  </picker>
</view>

index.wss

/* components/timePicker/index.wxss */

.input_base {
    border: 2rpx solid #ccc;
    padding-left: 10rpx;
    margin-right: 50rpx;
}

.input_h30 {
    height: 30px;
    line-height: 30px;
}

.col-1 {
    -webkit-box-flex: 1;
    box-flex: 1;
}

二、引用
/pages/index

index.json

{
    "usingComponents": {
        "time-picker": "../../../components/timePicker/index"
    }
}

index.wxml

<!-- index.wxml -->
<view class="title">时间选择</view>
<radio-group class="radio-group" bindchange="radioChange">
  <label class="radio" wx:for="{{items}}" wx:key="{{index}}">
    <radio value="{{item.value}}" checked="{{item.checked}}" />
    {{item.name}}
  </label>
</radio-group>
<time-picker mode="{{mode}}" class="picker" placeholder="请选择时间" bind:onPickerChange="onPickerChange"></time-picker>

index.js

//index.js
//获取应用实例
const app = getApp()

Page({
    data: {
        items: [{ name: '日期选择', value: 'date', checked: 'true' }, { name: '时间选择', value: 'time' }, { name: '日期时间选择', value: 'dateTime' }],
        mode: 'date'
    },
    onPickerChange(e) {//返回回调函数
        console.log("onPickerChange", e)
    },
    radioChange: function(e) {
        console.log(e)
        this.setData({
            mode: e.detail.value//获取类型;date年月日;time时分秒;dateTime年月日+时分秒
        })
    },
    onLoad: function() {

    },
})

三、效果
mode为date时
在这里插入图片描述
mode为time时在这里插入图片描述
mode为dateTime时
在这里插入图片描述

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值