当前位置:   article > 正文

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

微信小程序 日期时间选择器(年月日时分秒)

一、建立组件
/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()
        }
    }
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254

index.json

{
  "component": true,
  "usingComponents": {}
}
  • 1
  • 2
  • 3
  • 4

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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

二、引用
/pages/index

index.json

{
    "usingComponents": {
        "time-picker": "../../../components/timePicker/index"
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5

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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

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() {

    },
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/306549
推荐阅读
相关标签
  

闽ICP备14008679号