写微信小程序时,让用户选择时间时,必须考虑如下几个要素:
- 用户首选的时间必须是今天(当前时间)以后的
- 对应的年份、月份的对应的最大天数必须准确
具体实现如下
index.wxml
<picker range="{{name}}" mode="multiSelector" bindchange="bindchange" bindcolumnchange="bindcolumnchange" bindtap="dian" >
{{date}}
</picker>
// pages/demo1/demo1.js
Page({
data: {
date:"点击这里",
name: [
["2021","2022","2023","2024","2025","2026","2027","2028","2029","2030","2031"],
[],
[],
],
year1 :2021,
month1:null,
day1 :null,
},
dian(){
//确定初始的时间
let nowDate = new Date();
let year = nowDate.getFullYear();
let month = nowDate.getMonth() + 1 < 10 ? + (nowDate.getMonth() + 1)
: nowDate.getMonth() + 1;
let day = nowDate.getDate() < 10 ? + nowDate.getDate() : nowDate
.getDate();
let temp =this.data.name;
this.data.month1 = month;
this.data.year1 = year;
for(let i = month,j=0 ;i<=12;i++,j++){
temp[1][j] =i;
}
let max1 = new Date(year,month,0).getDate();
let j =0;
for(let i =0,j=day;j<=max1;i++,j++){
temp [2][i] = j;
}
this.setData({
name : temp
})
},
bindchange(e){
//e记录的是
let nowDate = new Date();
let year = nowDate.getFullYear();
let month = nowDate.getMonth() + 1 < 10 ? + (nowDate.getMonth() + 1)
: nowDate.getMonth() + 1;
let day = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate
.getDate();
var s=[];
for(var i =year;i<3000;i++){
s.push(i);
}
let a =e.detail.value[0]
let b =e.detail.value[1]
let c =e.detail.value[2]
let d =e.detail.value[3]
this.setData({
date : this.data.name[0][a]+"年-"+this.data.name[1][b]+"月-"+this.data.name[2][c]+"日"
})
},
bindcolumnchange(e){
//e记录的是滑轮的改变后的情况
let nowDate = new Date();
let year = nowDate.getFullYear();
let month = nowDate.getMonth() + 1 < 10 ? + (nowDate.getMonth() + 1)
: nowDate.getMonth() + 1;
let day = nowDate.getDate() < 10 ? + nowDate.getDate() : nowDate
.getDate();
let temp = this.data.name;
let coloum = e.detail.column;
let value = e.detail.value;
let year1 = this.data.year1;
let month1 =this.data.month1;
if(coloum ==0){
year1 = temp[0][value]
}if(coloum ==1 && year1 == year){
month1 = value+month;
}else if(coloum ==1 &&year1!=year){
month1 = value+1;
}
if(year1 == year){
temp[1]=[];
for(let i = month,j=0 ;i<=12;i++,j++){
temp[1][j] =i;
}
}if(year1 !=year){
temp[1]=[];
for(let i = 1,j=0 ;i<=12;i++,j++){
temp[1][j] =i;
}
}
if(month1 == month&&year1==year){
temp[2] =[];
let max1 = new Date(year,month,0).getDate();
let j =0;
for(let i =0,j=day;j<=max1;i++,j++){
temp [2][i] = j;
}
}else if(year1!=year) {
temp[2]=[]
let max1 = new Date(year1,month1,0).getDate();
let j =0;
for(let i =0,j=1;j<=max1;i++,j++){
temp [2][i] = j;
}
}if(year1 ==year&&month1!=month){
temp[2]=[]
let max1 = new Date(year1,month1,0).getDate();
let j =0;
for(let i =0,j=1;j<=max1;i++,j++){
temp [2][i] = j;
}}
this.setData({
name:temp,
year1:year1,
month1:month1
})
console.log(e);
console.log(year1);
console.log(month1);
}
})