微信小程序问题之picker-view日期选择器
项目需求截图,选择出生日期的时候需要用到微信的picker-view日期选择器
然后就发现官方picker-view组件有一些问题:
1、初始化日期不是当前日期
2、选择不同月份,日期都是从1-31号(其实不同月份 天数不同)
3、项目要求所选日期不能大于当前日期(既不能选择未来的日期)
在官方代码上,根据项目需求做了些修改
<view class="birthBox">
<label>选择生日</label>
<picker-view wx:if="{{years.length>0 && months.length>0 && days.length>0}}" style="width: 100%; height: 180rpx;" value="{{value}}" bindchange="bindChange">
<picker-view-column>
<view wx:for="{{years}}" wx:key="{{index}}">{{item}}年</view>
</picker-view-column>
<picker-view-column>
<view wx:for="{{months}}" wx:key="{{index}}">{{item}}月</view>
</picker-view-column>
<picker-view-column>
<view wx:for="{{days}}" wx:key="{{index}}">{{item}}日</view>
</picker-view-column>
</picker-view>
</view>
const date = new Date()
const nowYear = date.getFullYear()
const nowMonth = date.getMonth() +
const nowDay = date.getDate()
let daysInMonth = [, , , , , , , , , , , ]
// 根据年月 获取当月的总天数
let getDays = function(year, month) {
if (month === ) {
return ((year % === ) && ((year % ) !== )) || (year % === ) ? :
} else {
return daysInMonth[month-]
}
}
// 根据年月日设置当前月有多少天 并更新年月日数组
let setDate = function (year, month, day, _th){
let daysNum = year === nowYear && month === nowMonth ? nowDay : getDays(year, month)
day = day > daysNum ? : day
let monthsNum = year === nowYear ? nowMonth :
let years = []
let months = []
let days = []
let yearIdx =
let monthIdx =
let dayIdx =
// 重新设置年份列表
for (let i = ; i <= nowYear; i++) {
years.push(i)
}
years.map((v,idx)=> {
if (v === year){
yearIdx = idx
}
})
// 重新设置月份列表
for (let i = ; i <= monthsNum; i++) {
months.push(i)
}
months.map((v, idx) => {
if (v === month) {
monthIdx = idx
}
})
// 重新设置日期列表
for (let i = ; i <= daysNum; i++) {
days.push(i)
}
days.map((v, idx) => {
if (v === day) {
dayIdx = idx
}
})
_th.setData({
years: years,//年份列表
months: months,//月份列表
days: days,//日期列表
value: [yearIdx, monthIdx, dayIdx],
year: year,
month: month,
day: day
})
}
Page({
/**
* 页面的初始数据
*/
data: {
years: [],
months: [],
days: [],
year: nowYear,
month: nowMonth,
day: nowDay,
value: [, , ]
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
setDate(this.data.year, this.data.month, this.data.day, this)
},
bindChange: function (e) {
let val = e.detail.value
setDate(this.data.years[val[]], this.data.months[val[]], this.data.days[val[]], this)
}
})