最近自己写了一个微信小程序的时间选择器,复用性很高,就分享出来~欢迎指正。
我当前这个可以选择日期,也可以选择日期区间,可以选择上下午,通过配置实现。
效果图:
首先新建一个component。
.wxml文件内容:
<!-- 自定义时间筛选器 -->
<view hidden="{{!pickerShow}}">
<view class="picker-container " animation="{{animationData}}">
<view class="btn-box">
<view class="pick_btn" bindtap="_pickerHide">取消</view>
<view class='pick_btn' style="color: #19f" bindtap="_reset">{{config.clear}}</view>
</view>
<view class = 'input_time' hidden="{{!config.isTimeFrame}}">
<view class="view_time">
<view class = "time_text">开始日期</view>
<input type="text" class="disable_time {{isStartEnd == 1 ? 'start_active' : ''}}" placeholder="点击选择开始日期" disabled="true"
placeholder-class="disable-time-placeholder" value="{{startValue}}" bindtap="_getStartValue"/>
</view>
<view class="line-time">
<text>—</text>
</view>
<view class="view_time">
<view class = "time_text">结束日期</view>
<input type="text" class="disable_time {{isStartEnd == 2 ? 'end_active' : ''}}" placeholder="点击选择结束日期" disabled="true"
placeholder-class="disable-time-placeholder" value="{{endValue}}" bindtap="_getEndValue"/>
</view>
</view>
<picker-view class='sensorTypePicker' indicator-style='height: 35px;' bindchange="changeDateTime"
value="{{value}}" bindpickstart="handlePickStart" bindpickend="handlePickEndFirst">
<picker-view-column style="min-width: 70px;flex-shrink: 0">
<view class='picker-item' wx:for="{{years}}" wx:key='*this'>{{item}}年</view>
</picker-view-column>
<picker-view-column>
<view class='picker-item' wx:for="{{months}}" wx:key='*this'>{{item}}月</view>
</picker-view-column>
<picker-view-column>
<view class='picker-item' wx:for="{{days}}" wx:key='*this'>{{item}}日</view>
</picker-view-column>
<picker-view-column hidden="{{!config.isWeek}}">
<view class='picker-item' wx:for="{{weeks}}" wx:key='*this'>{{item}}</view>
</picker-view-column>
</picker-view>
<view class='determine-list'>
<button class="determine-submit-button determine-submit-large" bindtap="onConfirm">确定</button>
</view>
</view>
<!-- 遮罩 -->
<view class="sensorType-screen" bindtap="hideModal" animation="{{animationOpacity}}"/>
</view>
.js文件
/**
* 如何使用:
* 1,在组件.json文件引入
* 如:"time-picker": "/common/component/timeDataPiker/timeDataPiker"
* 2,在组件.wxss文件里加入模板
* 如: <time-picker pickerShow="{{isPickerShow}}" id="picker"
* wx:if="{{isPickerRender}}"config="{{pickerConfig}}" bind:timeData="searchTime"
* bind:timeReset="timeReset"></time-picker>
* 3,在组件js文件的data里加入配置项
* isPickerRender: false, 控制组件隐藏显示
* isPickerShow: false, 控制组件隐藏显示
* pickerConfig: {
* isTimeFrame: false, 是否显示开始结束时间框
* clear:'清空时间', 重置按钮文本
* isWeek:true 是否显示上午下午
* }
* 4,bind:timeData="searchTime" 获取时间 * 5,bind:timeReset="timeReset" 重置时间
*/
var now = new Date();
var yearData = now.getFullYear(); //得到年份
var monthData = now.getMonth();//得到月份
var monthDataRel = now.getMonth()+1;//得到月份
var dayData = now.getDate();//得到日期
Component({
behaviors: [],
properties: {
pickerShow: {
type: Boolean,
observer: function (val) { //弹出动画
if (val) {
let animation = wx.createAnimation({
duration: 500,
timingFunction: "ease"
});
let animationOpacity = wx.createAnimation({
duration: 500,
timingFunction: "ease"
});
setTimeout(() => {
animation.bottom(0).step();
animationOpacity.opacity(0.7).step();
this.setData({
animationOpacity: animationOpacity.export(),
animationData: animation.export()
})
}, 0);
} else {
let animation = wx.createAnimation({
duration: 100,
timingFunction: "ease"
});
let animationOpacity = wx.createAnimation({
duration: 500,
timingFunction: "ease"
});
animation.bottom(-320).step();
animationOpacity.opacity(0).step();
this.setData({
animationOpacity: animationOpacity.export(),
animationData: animation.export()
});
}
this.setData({
startValue: '',
endValue: '',
timeDataValue: '',
isSrue: true,
value: [yearData - 1990, monthData, dayData-1],
})
}
},
config: {
type: Object,
observer(newVal, oldVal, changedPath) {
}
},
},
data: {
startValue: '', //开始时间
endValue:'', // 结束时间
timeDataValue: '', // 不选择开始时间结束时间的时间
isPicking: false,
isStartEnd:0,
isSrue:true
}, // 私有数据,可用于模板渲染
lifetimes: {
// 生命周期函数,可以为函数,或一个在methods段中定义的方法名
attached: function () {
this._initTimeArray();
},
moved: function () { },
detached: function () { },
},
// 生命周期函数,可以为函数,或一个在methods段中定义的方法名
attached: function () { }, // 此处attached的声明会被lifetimes字段中的声明覆盖
ready: function () {
this._init();
},
pageLifetimes: {
// 组件所在页面的生命周期函数
show: function () { },
hide: function () { },
resize: function () { },
},
methods: {
// 取消
_pickerHide: function () {
this.setData({
pickerShow: false,
});
},
//滚动开始
handlePickStart: function (e) {
this.setData({
isPicking: true
})
},
//滚动结束
handlePickEndFirst: function (e) {
this.setData({
isPicking: false,
})
},
// 监控滑动
changeDateTime: function (e) {
this._calculation(e);
},
// 重新计算天数
_calculation: function (e) {
let year = 1990;
let month = 1;
let day = 1;
let week = '';
for (let i = 0; i <= e.detail.value.length; i++) {
if (i == 0) {
year = year + e.detail.value[i]
}
if (i == 1) {
month = month + e.detail.value[i]
}
if (i == 2) {
day = day + e.detail.value[i]
}
if (i == 3) {
if (e.detail.value[i] == 0) {
week = '—'
}
if (e.detail.value[i] == 1) {
week = '上午'
}
if (e.detail.value[i] == 2) {
week = '下午'
}
}
let days = [];
for (let i = 1; i <= this.getDays(year, month); i++) {
days.push(i);
}
this.setData({
days,
})
}
this._selectionPeriod(year, month, day, week);
},
// 重新计算天数
getDays: function (year, month) {
let daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (month === 2) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0
? 29
: 28;
} else {
return daysInMonth[month - 1];
}
},
// 获取默认时间为今日时间
_init:function() {
this.setData({
value: [yearData - 1990, monthData, dayData-1],
});
},
// 初始化时间列表
_initTimeArray:function() {
const date = new Date();
const years = [];
const months = [];
const days = [];
const weeks = ['—', '上午', '下午'];
for (let i = 1990; i <= date.getFullYear()+50; i++) {
years.push(i)
}
for (let i = 1; i <= 12; i++) {
months.push(i)
}
for (let i = 1; i <= 31; i++) {
days.push(i)
}
this.setData({
years,
months,
days,
weeks
})
},
// 重置
_reset:function(){
this.setData({
endValue: '',
startValue: '',
timeDataValue: ''
})
if (this.data.config.isTimeFrame) {
this.setData({
isSrue: false,
});
} else {
this.triggerEvent('timeReset', { 'timeData': this.data.timeDataValue });
this.setData({
pickerShow: false,
});
}
},
// 点击选择开始时间
_getStartValue: function (e){
var y = ''
var m = ''
var d = ''
for (let i = 1; i <= this.data.value.length; i++){
if (i = 1) {
y = this.data.value[i-1]+1990
}
if (i = 2) {
m = this.data.value[i-1]+1
}
if (i = 3) {
d = this.data.value[i-1]+1
}
}
this.setData({
startValue: y + '-' + m + '-' + d,
isStartEnd: 1,
})
},
// 点击选择结束时间
_getEndValue: function(){
var y = ''
var m = ''
var d = ''
for (let i = 1; i <= this.data.value.length; i++) {
if (i = 1) {
y = this.data.value[i - 1] + 1990
}
if (i = 2) {
m = this.data.value[i - 1] + 1
}
if (i = 3) {
d = this.data.value[i - 1] + 1
}
}
this.setData({
endValue: y + '-' + m + '-' + d,
isStartEnd: 2,
})
},
// 滑动选择时间
_selectionPeriod: function (year, mouth, day, week){
if (this.data.config.isTimeFrame) {
if (this.data.isStartEnd ==1) {
this.setData({
startValue: year + '-' + mouth + '-' + day,
})
} else if (this.data.isStartEnd == 2) {
this.setData({
endValue: year + '-' + mouth + '-' + day,
})
}
} else {
this.setData({
timeDataValue: year + '-' + mouth + '-' + day + '-' + week,
})
}
},
// 确认
onConfirm: function(){
if (this.data.isSrue) {
if (this.data.isPicking) { return }
if (this.data.config.isTimeFrame) {
if (!this.data.startValue) {
wx.showToast({
icon: "none",
title: "请选择开始时间"
});
return
}
if (!this.data.endValue) {
wx.showToast({
icon: "none",
title: "请选择结束时间"
});
return
}
var startList = new Date(this.data.startValue);
var endList = new Date(this.data.endValue);
if (startList.getTime() <= endList.getTime()) {
var timeData =
this.triggerEvent('timeData', { 'startData': this.data.startValue, 'endData': this.data.endValue });
this.setData({
pickerShow: false,
});
} else {
wx.showToast({
icon: "none",
title: "结束时间不能早于开始时间"
});
return
}
} else {
if (!this.data.timeDataValue) {
this.triggerEvent('timeData', { 'timeData': yearData + '-' + monthDataRel + '-' + dayData + '-' + '—' });
this.setData({
pickerShow: false,
});
} else {
this.triggerEvent('timeData', { 'timeData': this.data.timeDataValue });
this.setData({
pickerShow: false,
});
}
}
} else {
this.triggerEvent('resetConfirm', { 'startData': this.data.startValue, 'endData': this.data.endValue });
this.setData({
pickerShow: false,
});
}
}
}
})
.sjon文件
{
"component": true,
"usingComponents": {}
}
.wxss文件
.picker-item{
line-height: 50px;
display: flex;
justify-content: center;
align-items: center;
}
/* 自定义时间 */
.picker-container {
display: flex;
flex-direction: column;
/* justify-content: center; */
align-items: center;
width: 100%;
overflow: hidden;
position: fixed;
bottom: -320px;
left: 0;
/* height: 0; */
transition: height 0.5s;
z-index: 2000;
background: white;
/* border-bottom: 1px solid #E8E8E8; */
}
.sensorType-screen{
width: 100vw;
/* height:400rpx; */
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: #333333;
opacity: 0;
overflow: hidden;
z-index: 1999;
color: #fff;
}
.sensorTypePicker{
width: 690rpx;
height: 130px;
/* padding: 45px 0; */
}
.picker-item{
line-height: 50px;
display: flex;
justify-content: center;
align-items: center;
font-size: 16px;
/* overflow: hidden; */
}
.box{
padding: 0 10px;
}
/* 至 */
.to{
width:100%;
display: flex;
justify-content: center;align-items: center;
color:rgb(138,138,138);
font-size: 30rpx;
/* font-size:30rpx; */
}
.btn-box{
width: 100%;
display: flex;
height: 90rpx;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid #eee;
}
.pick_btn{
padding: 7px 15px;
color: #666666;
/* background-color: #159; */
}
/*输入框中的时间样式*/
.input_time {
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
/* border-bottom: 1px solid #eee; */
}
.view_time {
padding: 24rpx 30rpx;
}
.time_text {
font-size: 24rpx;
color: #999;
}
.disable_time {
font-size: 30rpx;
background-color: #F0F2F5;
color: #666;
margin-top: 20rpx;
width: 230rpx;
padding: 12rpx 30rpx;
border-radius: 6rpx;
}
.disable-time-placeholder{
color: #999999;
font-size: 24rpx;
}
.determine-list{
margin-top: 24rpx;
width: 94%;
}
.determine-submit-button{
font-size: 30rpx;
background: linear-gradient(to bottom,#289CFF,#51CBFF);
color: #FFFFFF;
margin-bottom: 36rpx;
}
.determine-submit-button::after{
border: 0;
}
.determine-submit-large{
height: 72rpx;
line-height: 72rpx;
width: 100%;
border-radius: 12rpx;
}
.line-time{
margin-top: 40rpx;
color: #999999;
}
.start_active, .end_active{
border:2rpx #289CFF solid;
}
如何使用(从很多代码里截的,粘贴修改可用)
1,打开要使用的page的json文件配置路径
{
"usingComponents": {
"time-picker": "/common/component/timeDataPiker/timeDataPiker",
}
}
2,在wxml文件中引入
<time-picker pickerShow="{{isPickerShow}}" wx:if="{{isPickerRender}}"
config="{{pickerConfig}}" bind:timeData="searchTime" bind:timeReset="timeReset"></time-picker>
3,在js文件控制显示
const app = getApp();
var util = require('../../../utils/util.js');
Page({
/**
* 页面的初始数据
*/
data: {
// 时间控件开始
isPickerRender: false,
isPickerShow: false,
pickerConfig: {
isTimeFrame: false,
clear:'清空时间',
isWeek:true
},
// 时间控件结束
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
},
// 按照选择日期搜索
searchTime: function (e) {
if (e.detail.timeData){
let data = e.detail.timeData.split('-')
var time = ''
var text = ''
for(var i in data){
if (data[i] == '—') {
time = data[0] + '-' + data[1] + '-' + data[2] + 'T00:00:00' + ',' + data[0] + '-' + data[1] + '-' + data[2] + 'T23:59:59';
text = data[1] + '-' + data[2]+' '
}
if (data[i] == '上午') {
time = data[0] + '-' + data[1] + '-' + data[2] + 'T00:00:00' + ',' + data[0] + '-' + data[1] + '-' + data[2] + 'T11:59:59';
text = data[1] + '-' + data[2] + ' ' + data[i]
}
if (data[i] == '下午') {
time = data[0] + '-' + data[1] + '-' + data[2] + 'T12:00:00' + ',' + data[0] + '-' + data[1] + '-' + data[2] + 'T23:59:59'
text = data[1] + '-' + data[2] + ' ' + data[i]
}
}
}
this.setData({
createTime: time,
timeText: text
})
this.getDelivery(5, this.data.inputSuccessValue, this.data.createTime);
},
// 显示或隐藏时间插件
pickerShow: function () {
this.setData({
isPickerShow: true,
isPickerRender: true,
});
},
//可送货订单时间插件
deliveryPickerShow: function() {
this.setData({
isDeliveryPickerShow: true,
isDeliveryPickerRender: true,
resetDeliveryTime: false
})
},
// 清除时间
timeReset:function(e){
this.setData({
createTime: e.detail.timeData
})
this.getDelivery(5, this.data.inputSuccessValue, this.data.createTime);
},
timeDeliveryReset: function(e) {
this.setData({
resetDeliveryTime: true
})
},
})