程序需要用到时间控件,于是上网找了一下资料,整理了一下,这篇讲的是最大选择日期为当前日期,下一篇写不限制最大选择日期。
有点不知道怎么处理,试了好多次,大于10之前的数字如何在前面加0,如果加了判断的话,别的就会出问题。欢迎大佬指教
给出效果图:
贴出代码:
wxml:
<view class="time_text">{{year}}-{{month}}-{{day}}</view>
<view class="time_title">
<view class="time_title_text">年</view>
<view class="time_title_text">月</view>
<view class="time_title_text">日</view>
</view>
<picker-view wx:if="{{years.length>0 && months.length>0 && days.length>0}}" indicator-style="height: 50px;" class="view_picker" value="{{value}}" bindchange="bindChange">
<picker-view-column class="view_picker_column">
<view wx:for="{{years}}" class="view_picker_text" wx:key="{{index}}">{{item}}</view>
</picker-view-column>
<picker-view-column class="view_picker_column">
<view wx:for="{{months}}" class="view_picker_text" wx:key="{{index}}">{{item}}</view>
</picker-view-column>
<picker-view-column class="view_picker_column">
<view wx:for="{{days}}" class="view_picker_text" wx:key="{{index}}">{{item}}</view>
</picker-view-column>
</picker-view>
js:
const date = new Date()
const nowYear = date.getFullYear()
const nowMonth = date.getMonth() + 1
const nowDay = date.getDate()
let daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
// 根据年月获取当月的总天数
let getDays = function (year, month) {
if (month === 2) {
return ((year % 4 === 0) && ((year % 100) !== 0)) || (year % 400 === 0) ? 29 : 28
} else {
return daysInMonth[month - 1]
}
}
// 根据年月日设置当前月有多少天 并更新年月日数组
let setDate = function (year, month, day, _this) {
let daysNum = year === nowYear && month === nowMonth ? nowDay : getDays(year, month)
day = day > daysNum ? 1 : day
let monthsNum = year === nowYear ? nowMonth : 12
let years = []
let months = []
let days = []
let yearIndex = 9999
let monthIndex = 0
let dayIndex = 0
// 重新设置年份列表
for (let i = 1990; i <= nowYear; i++) {
years.push(i)
}
years.map((v, idx) => {
if (v === year) {
yearIndex = idx
}
})
// 重新设置月份列表
for (let i = 1; i <= monthsNum; i++) {
var k = i;
months.push(k)
}
months.map((v, idx) => {
if (v === month) {
monthIndex = idx
}
})
// 重新设置日期列表
for (let i = 1; i <= daysNum; i++) {
var k = i;
days.push(k)
}
days.map((v, idx) => {
if (v === day) {
dayIndex = idx
}
})
_this.setData({
//时间列表参数
years: years,
months: months,
days: days,
//选中的日期
year: year,
month: month,
day: day,
value: [yearIndex, monthIndex, dayIndex],
})
}
Page({
data: {
//时间列表参数
flag: false,
years: [],
months: [],
days: [],
//选中的日期
year: nowYear,
month: nowMonth,
day: nowDay,
value: [9999, 1, 1],
},
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[0]], this.data.months[val[1]], this.data.days[val[2]], this)
}
})
版权声明:本文为cchhzzyy原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。