小程序只有分别的日期、时间选择器,故用多级选择实现需求
效果图:
html
<picker mode="multiSelector" bindchange="bindMultiPickerChange" bindcolumnchange="bindMultiPickerColumnChange" value="{{multiIndex}}" range="{{multiArray}}">
<!-- 内部为点击选择前的展示内容,此处为时间+箭头图标 -->
<view>
<view>{{eventTime}}</view>
<image src="../resources/icon_right.png" />
</view>
</picker>
js
export default class reportType extends wepy.component {
data = {
multiArray: [[], [], [], [], []],
multiIndex: [0, 0, 0, 0, 0],
choose_year: '',
eventTime: '' // 最终选择的时间
}
methods = {
// 获取时间日期,点击确定时调用
bindMultiPickerChange: function(e) {
this.multiIndex = e.detail.value
const index = this.multiIndex;
const year = this.multiArray[0][index[0]];
const month = this.multiArray[1][index[1]];
const day = this.multiArray[2][index[2]];
const hour = this.multiArray[3][index[3]];
const minute = this.multiArray[4][index[4]];
this.eventTime = year + '-' + month + '-' + day + ' ' + hour + ':' + minute
},
// 监听picker的滚动事件
bindMultiPickerColumnChange: function(e) {
if (e.detail.column == 0) {
// 获取年份,为后续计算闰年做准备
let choose_year = this.multiArray[e.detail.column][e.detail.value];
this.choose_year = choose_year
}
if (e.detail.column == 1) {
// 切换月份时,调整日的选择范围
this.setDayArray(e.detail.value)
}
this.multiIndex[e.detail.column] = e.detail.value;
},
}
loopArray(start, end) {
const list = []
for (let i = start; i <= end; i++) {
if (i < 10) {
i = "0" + i;
}
list.push("" + i);
}
return list
}
setDayArray(monthIndex, monthNum = null) {
let num = monthNum || parseInt(this.multiArray[1][monthIndex]);
if (num == 1 || num == 3 || num == 5 || num == 7 || num == 8 || num == 10 || num == 12) {
//判断31天的月份
this.multiArray[2] = this.loopArray(1, 31)
} else if (num == 4 || num == 6 || num == 9 || num == 11) {
//判断30天的月份
this.multiArray[2] = this.loopArray(1, 30)
} else if (num == 2) {
//判断2月份天数
let year = parseInt(this.choose_year);
if (((year % 400 == 0) || (year % 100 != 0)) && (year % 4 == 0)) {
this.multiArray[2] = this.loopArray(1, 29)
} else {
this.multiArray[2] = this.loopArray(1, 28)
}
}
this.$apply()
}
init() {
const date = new Date();
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hours = date.getHours();
const minutes = date.getMinutes();
this.eventTime = year + '-' + month + '-' + day + ' ' + hour + ':' + minute // 默认展示当前的日期时间
this.choose_year = year
this.multiArray = [this.loopArray(2018, year + 5), this.loopArray(1, 12), [], this.loopArray(0, 24), this.loopArray(0, 60)] // 分别为年、月、日、时、分的选择范围;其中年份范围从2018 - 当前年加5
this.setDayArray(0, date.getMonth()) // 计算当前月份的 日 的范围
this.multiIndex = [year - 2018, month - 1, day - 1, hours, minutes] // 选择器内的选项值也初始化为当前的日期时间
this.$apply()
}
onLoad() {
this.init() // 加载选择框内数据
}
}