由于原生的picker页面只能使用默认的无法自定义,在开发中有特殊需求时就需要自定义日期选择器
先看效果,页面可以在css文件中自定义
代码:
datePicker.js
const dateUtils = require('../../../../utils/util.js')
// 初始化日期模态框数据
let date = new Date();
let years = [];
let months = [];
let days = [];
let hours = [];
let minutes = [];
for (let i = date.getFullYear() - 4; i <= (date.getFullYear() + 1); i++) {
years.push(i + "年")
}
for (let i = 1; i <= 12; i++) {
if (i < 10) {
months.push("0" + i + "月")
} else {
months.push(i + "月")
}
}
for (let i = 1; i <= 31; i++) {
if (i < 10) {
days.push("0" + i + "日");
} else {
days.push(i + "日");
}
}
for (let i = 0; i <= 23; i++) {
hours.push(i + "")
}
for (let i = 0; i <= 59; i++) {
minutes.push(i + "")
}
Component({
// options: {
// multipleSlots: true // 在组件定义时的选项中启用多slot支持
// },
properties: {
// title: { // 属性名
// type: String, // 类型(必填),目前接受的类型包括:String, Number, Boolean, Object, Array, null(表示任意类型)
// value: '' // 属性初始值(可选),如果未指定则会根据类型选择一个
// }
// timeValue: {
// type: Array,
// value: "标题"
// },
// years: {
// type: Array,
// value: "年"
// },
// months: {
// type: Array,
// value: "月"
// },
// days: {
// type: Array,
// value: "日"
// },
// hours: {
// type: Array,
// value: "小时"
// },
// minutes: {
// type: Array,
// value: "分钟"
// }
dateItem: {
type: String,
value: "日期"
},
},
data: {
modalName: null,
startDate: "",
endDate: "",
userName: "",
farmerId: "",
timeValue: [2, 3, 4],
changeFlag: false,
value: [0, 1, 1],
openFlag: true, //1日期控件显示 2控件滚动选择 底部页面不滚动
years: years, //时间可选范围模态框数据
months: months,
days: days,
hours: hours,
minutes: minutes,
year: '', //时间值
month: '',
day: '',
hour: '',
minute: '',
startTime: dateUtils.stampToDate(),
selectDate: ""
},
methods: {
//取消
cancelBtn() {
// this.triggerEvent("cancelBtn");
this.hideModal()
},
//确认
confirmBtn(e) {
if (this.data.selectDate == "") {
this.triggerEvent("confirmBtn", this.data.dateItem);
} else {
this.triggerEvent("confirmBtn", this.data.selectDate);
}
this.hideModal();
// this.bindChangeEvent();
// this.triggerEvent("bindChangeEvent",e.detail);
},
// 调用父组件 事件
bindChangeEvent(e) {
// this.triggerEvent("bindChangeEvent",e.detail);
console.log("datePicker", e);
let changeDate = "";
let year1 = years[e.detail.value[0]].replace("年", "-").trim();
let month1 = months[e.detail.value[1]].replace("月", "-").trim();
let day1 = this.data.days[e.detail.value[2]].replace("日", "").trim();
this.setData({
selectDate: year1 + month1 + day1
});
// console.log("year1", year1+month1+day1);
// console.log("days", days);
this.setData({
timeValue: e.detail.value
});
let val = e.detail.value;
const year = this.data.years[val[0]];
const month = this.data.months[val[1]];
const day = this.data.days[val[2]];
const hour = this.data.hours[val[3]];
const minute = this.data.minutes[val[4]];
//如果点击月份 那么后面日跟着变换数据
let days = [];
const dayNum = dateUtils.mGetDate(year.substr(0, year.length - 1), month.substr(0, month.length - 1));
for (let i = 1; i <= dayNum; i++) {
if (i < 10) {
days.push("0" + i + "日");
} else {
days.push(i + "日");
}
}
this.setData({
days,
year,
month,
day,
hour,
minute,
changeFlag: true,
})
},
//显示
showModal: function () {
this.setData({
modalName: "DialogModal1"
})
let dateArr = this.data.dateItem.split("-");
console.log("dateArr", dateArr);
let yearNum = this.getArrayIndex(years, dateArr[0] + "年");
let monthNum = this.getArrayIndex(months, dateArr[1] + "月");
let dayNum = this.getArrayIndex(this.data.days, dateArr[2] + "日");
this.setData({
timeValue: [yearNum, monthNum, dayNum]
});
},
hideModal: function () {
this.setData({
modalName: null
})
},
getArrayIndex(arr, obj) {
let i = arr.length;
while (i--) {
if (arr[i] === obj) {
return i;
}
}
return -1;
}
},
});
datePicker.json
{
"component": true,
"usingComponents": {
}
}
datePicker.wxml
<view class="cu-modal {{modalName=='DialogModal1'?'show':''}}">
<!-- <view class="cu-dialog">-->
<!-- <view class="cu-bar dialog_title_bg justify-end">-->
<!-- <view class="content" style="color: white">请选择过滤条件</view>-->
<!-- <view class="action" bindtap="hideModal">-->
<!-- <text class="cuIcon-close text-white"></text>-->
<!-- </view>-->
<!-- </view>-->
<!-- <slot></slot>-->
<!-- <view >日期选择</view>-->
<!-- 日期模态框 -->
<view class="date-picker-bg"></view>
<view class="date-picker-view">
<view class = "model_picker">
<view class = "button_model">
<text catchtap='cancelBtn' >取消</text>
<text catchtap='confirmBtn' >确定</text>
</view>
<view class = "cont_model">
<picker-view indicator-class="indicator-style-view"
style="width: 100%; height: 300px;" value="{{timeValue}}" catchchange="bindChangeEvent">
<!-- 年 -->
<picker-view-column wx:if="{{years.length > 0}}">
<view class="{{timeValue[0]==index?'pickerSelected':''}}" wx:for="{{years}}" wx:key="{{index}}" style="line-height: 50px;">{{item}}</view>
</picker-view-column>
<!-- 月 -->
<picker-view-column wx:if="{{months.length > 0}}">
<view class="{{timeValue[1]==index?'pickerSelected':''}}" wx:for="{{months}}" wx:key="{{index}}" style="line-height: 50px">{{item}}</view>
</picker-view-column>
<!-- 日 -->
<picker-view-column wx:if="{{days.length > 0}}">
<view class="{{timeValue[2]==index?'pickerSelected':''}}" wx:for="{{days}}" wx:key="{{index}}" style="line-height: 50px">{{item}}</view>
</picker-view-column>
<!-- <!– 时 –>-->
<!-- <picker-view-column wx:if="{{hours.length > 0}}">-->
<!-- <view wx:for="{{hours}}" wx:key="{{index}}" style="line-height: 50px">{{item}}</view>-->
<!-- </picker-view-column>-->
<!-- <!– 分 –>-->
<!-- <picker-view-column wx:if="{{minutes.length > 0}}">-->
<!-- <view wx:for="{{minutes}}" wx:key="{{index}}" style="line-height: 50px">{{item}}</view>-->
<!-- </picker-view-column>-->
</picker-view>
</view>
</view>
</view>
</view>
datePicker.wxss
/* ==================
模态窗口
==================== */
.cu-modal {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1110;
opacity: 0;
outline: 0;
text-align: center;
-ms-transform: scale(1.185);
transform: scale(1.185);
backface-visibility: hidden;
perspective: 2000rpx;
background: rgba(0, 0, 0, 0.6);
transition: all 0.1s ease-in-out 0s;
pointer-events: none;
}
.cu-modal::before {
content: "\200B";
display: inline-block;
height: 100%;
vertical-align: middle;
}
.cu-modal.show {
opacity: 1;
transition-duration: 0.3s;
-ms-transform: scale(1);
transform: scale(1);
overflow-x: hidden;
overflow-y: auto;
pointer-events: auto;
}
.date-picker-bg {
position: absolute;
top: 0;
z-index: 10000;
width: 100%;
height: 100%;
background: #000;
opacity: 0.3;
}
.date-picker-view {
position: absolute;
bottom: 0;
z-index: 999999;
width: 100%;
background: #fff;
}
picker-view-column {
text-align: center;
}
view.model_picker {
position: relative;
}
.button_model {
height: 80rpx;
width: 100%;
background: #fff;
position: relative;
border-bottom: 1px solid #d9d9d9;
}
.button_model text {
color: #007aff;
position: absolute;
background: transparent;
border: none;
line-height: 80rpx;
}
.button_model text:first-child {
left: 32rpx;
}
.button_model text:last-child {
right: 32rpx;
}
.indicator-style-view {
height: 50px;
background-color: #0288d112;
border-top: 5rpx solid #4CD964;
border-bottom: 5rpx solid #4CD964;
color: red
}
.pickerSelected {
color: #D90C04;
}
utils.js
// 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(':')
// }
const formatHour = 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 hour
};
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(':')
}
const formatDate = 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(':')
}
const formatData = 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('-')
}
const formatDataBefore7 = date => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()-7
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return [year, month, day].map(formatNumber).join('-')
}
const formatDataBefore3 = date => {
const year = date.getFullYear();
let month;
let day;
if (date.getDate() < 4) {
month = date.getMonth();
} else {
month = date.getMonth() + 1;
}
if (date.getDate() < 4) {
if (date.getMonth() === 2) {
day = 28 - (3 - date.getDate());
} else if (date.getMonth() === 1 || date.getMonth() === 3 || date.getMonth() === 5 || date.getMonth() === 7 || date.getMonth() === 8 || date.getMonth() === 10 || date.getMonth() === 12) {
day = 31 - (3 - date.getDate());
} else {
day = 30 - (3 - date.getDate());
}
} else {
day = date.getDate() - 3;
}
return [year, month, day].map(formatNumber).join('-');
}
const formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
// 转换时间
const getDate = (year, month, day, hour, minute) => {
const newyear = year.substr(0, year.length - 1);
const setmonth = month.substr(0, month.length - 1);
const newmonth = setmonth < 10 ? '0' + setmonth : setmonth;
const setday = day.substr(0, day.length - 1);
const newday = setday < 10 ? '0' + setday : setday;
// const sethour = hour.substr(0, hour.length - 1);
const newhour = hour < 10 ? '0' + hour : hour;
// const setminute = minute.substr(0, minute.length - 1);
const newminute = minute < 10 ? '0' + minute : minute;
return newyear + '-' + newmonth + '-' + newday + ' ' + newhour + ":" + newminute;
};
// 将时间戳转换为时间
const stampToDate = (date) => {
let now;
if (date) {
now = new Date(date)
} else {
now = new Date()
}
let y = now.getFullYear(),
m = now.getMonth() + 1,
d = now.getDate(),
h = now.getHours(), //获取当前小时数(0-23)
f = now.getMinutes(),
n = (Math.ceil((now.getMinutes()) / 10)) * 10; //获取当前分钟数(0-59) 取整数
return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " " + (h < 10 ? "0" + h : h) + ":" + (f < 10 ? "0" + f : f);
};
//根据年月 获取天数
const mGetDate = (year, month) => {
var d = new Date(year, month, 0);
return d.getDate();
}
//根据时间2019-01-02 09:12 得到 ['2019','1','2','9','12']
const getArrFromDate = (str) => {
let arr = [];
let arr1 = str.split(' ');
let arr2 = (arr1[0]).split('-');
let arr3 = arr1[1].split(':');
arr = arr2.concat(arr3);
arr[1] = arr[1].startsWith('0') ? arr[1].substr(1, arr[1].length) : arr[1];
arr[2] = arr[2].startsWith('0') ? arr[2].substr(1, arr[2].length) : arr[2];
arr[3] = arr[3].startsWith('0') ? arr[3].substr(1, arr[3].length) : arr[3];
arr[4] = arr[4].startsWith('0') ? arr[4].substr(1, arr[4].length) : arr[4];
return arr;
};
module.exports = {
formatTime: formatTime,
formatData: formatData,
formatDate: formatDate,
formatDataBefore7: formatDataBefore7,
formatDataBefore3: formatDataBefore3,
formatHour: formatHour,
getDate,
stampToDate,
mGetDate,
getArrFromDate,
}
调用需要的参数
index.wxml
<datePicker
id="datePicker"
dateItem="2020-07-09"
bind:confirmBtn="confirmBtn"
bind:bindChangeEvent="bindChangeEvent"
>
</datePicker>