在原生的小程序组件中是没有获取datetime类型的组件的,当你需要设置年月日时分的时候就需要自己定义组件了,
这里使用的uniapp来写的
首先定义wxml层:
html
<view class="form-item">
<text class="form-label required">线索发现时间</text>
<picker
class="form-picker"
mode="multiSelector"
:range="range"
:value="pickerIdx"
@change="onDateTimeChange"
@columnchange="onColumnChange"
>
<view class="picker-value">
{{ formData.findTime || '请选择线索发现时间' }}
</view>
</picker>
</view>
之后就是
JS代码
需要返回五个数据,但是因为日是动态的所以需要getDays()函数来自己获取。
定义数组,有五列,分别是年月日时分
主要就是监听着数组中的五列,数组中的每一列又会变化,每转动一次转盘,就会重新赋值给变量,
javascript
export default {
data() {
/* 五列数据源 */
const years = Array.from({ length: 11 }, (_, i) => 2020 + i);
const months = Array.from({ length: 12 }, (_, i) => i + 1);
const hours = Array.from({ length: 24 }, (_, i) => i);
const minutes = Array.from({ length: 60 }, (_, i) => i);
return {
years, months, hours, minutes,
range: [], // 五列
pickerIdx: [0, 0, 0, 0, 0],
/* 其余业务字段 */
formData: {
findTime: '', // 最终字符串 2025-09-19 14:30
location: '',
contact: '',
description: '',
latitude: '',
longitude: '',
isAnonymous: 0,
status: 2,
images: []
},
/* 其余原 data ... */
};
},
onLoad(options) {
this.initRange(); // 关键:初始化 picker
/* 其余 onLoad 逻辑 ... */
},
methods: {
/* ---------- 日期时间选择 ---------- */
getDays(y, m) {
return new Date(y, m, 0).getDate();
},
initRange() {
const now = new Date();
const y = now.getFullYear();
const m = now.getMonth() + 1;
const d = now.getDate();
const h = now.getHours();
const mm = now.getMinutes();
this.pickerIdx = [
this.years.indexOf(y),
m - 1,
d - 1,
h,
mm
];
const days = Array.from({ length: this.getDays(y, m) }, (_, i) => i + 1);
this.range = [this.years, this.months, days, this.hours, this.minutes];
},
onColumnChange(e) {
const col = e.detail.column;
const row = e.detail.value;
const idx = [...this.pickerIdx];
idx[col] = row;
if (col === 0 || col === 1) { // 年或月变化
const year = this.years[idx[0]];
const month = this.months[idx[1]];
const days = Array.from({ length: this.getDays(year, month) }, (_, i) => i + 1);
this.range[2] = days;
if (idx[2] >= days.length) idx[2] = days.length - 1;
this.pickerIdx = idx;
}
},
onDateTimeChange(e) {
const idx = e.detail.value;
const y = this.years[idx[0]];
const m = String(this.months[idx[1]]).padStart(2, '0');
const d = String(this.range[2][idx[2]]).padStart(2, '0');
const h = String(this.hours[idx[3]]).padStart(2, '0');
const mm = String(this.minutes[idx[4]]).padStart(2, '0');
this.formData.findTime = `${y}-${m}-${d} ${h}:${mm}`;
},
}
};