实现此类的日期选择
1. 引入
2.使用组件
<view class="mask" v-if="timeShow">
<view style="width:100%;height:100%;" @click="close"></view>
<view class="dialogshare">
<view style="overflow-y: auto;overflow-x: hidden;">
<h-datetime-picker ref="pickerDate" @reset="reset" @confirm="confirm" @close="close" :successStartTime="successStartTime" :successEndTime="successEndTime"></h-datetime-picker>
</view>
</view>
</view>
// 关闭/重置 事件
reset(){
console.log('点击了重置');
},
// 选择后成功事件做处理的地方
confirm(e){
console.log('点击了确定',e);
},
根据具体需求更改的 h-datetime-picker.vue 文件
<template>
<view>
<uni-popup ref="popup" @maskClick="close">
<view class="popup-box">
<view class="display-flex align-items-center space-between" style="padding: 30rpx;">
<view style="width: 20rpx;height: 1px;"></view>
<view style="font-weight: 600;font-size: 28rpx;color: #333333;letter-spacing: 1px;">时间选择</view>
<image src="/static/images/timeClose.png" style="width: 30rpx;height: 30rpx;" @click="reset">
</image>
</view>
<view class="title" style="padding-top: 30rpx;">
<view class="tabs-box" v-if="mode=='all'">
<view v-for="(item,index) in tabs" :key="index" class="tabs-item" @click="tabChange(index)"
:class="{'tabs-check':index==tabIndex}">
<text class="item-text" style="margin-bottom: 24px;">{{item}}</text>
<view v-if="index==tabIndex"
style="height: 6rpx;background: #116C40;text-align: center;width: 36rpx;margin: 24rpx auto;">
</view>
</view>
</view>
<view v-else class="title-text">
<text class="text">{{mode=='multiple'?'日期筛选':'月份选择'}}</text>
</view>
<uni-icons type="closeempty" class="close" size="16" @click="close"></uni-icons>
</view>
<view>
<view class="options-box" v-if="tabIndex">
<view style="font-weight: 400;font-size: 28rpx;color: #333333;">交易时间</view>
<view class="time-container" style="margin-top: 36rpx;">
<view v-for="(item,index) in options" :key="index" class="timeStyle"
@click="optionSelect(index)" :class="{'timeStyle2':opIndex==index}">
{{item}}
</view>
</view>
<view style="font-weight: 400;font-size: 28rpx;color: #333333;">自定义</view>
<view class="flex row-between" style="margin-top: 40rpx;">
<view class="option" :class="{'option-check':op1Index==0}"
style="width: 306rpx;padding-left: 0;padding-right: 0;display: flex;align-items: center;"
@click="optionChange(0)">
<text class="option-text">{{startDate}}</text>
<image src="/static/images/downArrow.png" style="width: 20rpx;height: 10rpx;"></image>
</view>
<view style="font-weight: 500;font-size: 24rpx;color: #333333;margin: 0 15px;">至</view>
<view class="option" :class="{'option-check':op1Index==1}"
style="width: 306rpx;padding-left: 0;padding-right: 0;display: flex;align-items: center;"
@click="optionChange(1)">
<text class="option-text">{{endDate}}</text>
<image src="/static/images/downArrow.png" style="width: 20rpx;height: 10rpx;"></image>
</view>
</view>
</view>
<view class="picker-body">
<picker-view class="picker-view" :value="valueArr" @change="change" @touchend="touchend">
<picker-view-column v-if="params.year">
<view class="column-item display-flex align-items-center space-center"
v-for="(item,index) in years" :key="index">
<text class="column-item-text">{{item}}年</text>
</view>
</picker-view-column>
<picker-view-column v-if="params.month">
<view class="column-item display-flex align-items-center space-center"
v-for="(item,index) in months" :key="index">
<text class="column-item-text">{{formatNumber(item)}}月</text>
</view>
</picker-view-column>
<picker-view-column v-if="params.day && tabIndex">
<view class="column-item display-flex align-items-center space-center"
v-for="(item,index) in days" :key="index">
<text class="column-item-text">{{formatNumber(item)}}日</text>
</view>
</picker-view-column>
<!-- <picker-view-column v-if="params.half">
<view class="column-item" v-for="(item,index) in halfs" :key="index">
<text class="column-item-text">{{item.label}}</text>
</view>
</picker-view-column> -->
</picker-view>
</view>
<view style="border-top: 1px solid #EFEFEF;margin-bottom: 10rpx;">
<view @click="getResult"
style="height: 88rpx;background: #e6f1eb;border-radius: 20rpx;margin: 20rpx 40rpx;line-height: 88rpx;font-weight: 500;font-size: 28rpx;color: #FFFFFF;text-align: center;letter-spacing: 1px;">
确定</view>
</view>
</view>
</view>
</uni-popup>
</view>
</template>
<script>
import timeFormat from "../../js/timeFormat.js"
export default {
props: {
// picker中需要显示的参数
params: {
type: Object,
default () {
return {
year: true,
month: true,
day: true,
half: !false
};
}
},
// 默认显示的时间,2025-07-02 || 2025-07-02 13:01:00 || 2025/07/02
defaultTime: {
type: String,
default: timeFormat(new Date(), 'yyyy-mm-dd')
},
// 自定义时间选项模式month:月 day:天
optionMode: {
type: String,
default: 'month'
},
//选择器模式 single:单月 multiple:多月 all:都包括(暂时有bug 勿用)
mode: {
type: String,
default: 'all'
},
endTime: {
type: String,
default: timeFormat(new Date(), 'yyyy-mm-dd')
},
successStartTime: {
type: String,
default: timeFormat(new Date(), 'yyyy-mm-dd')
},
successEndTime: {
type: String,
default: timeFormat(new Date(), 'yyyy-mm-dd--')
},
},
data() {
return {
timeFormat,
years: [],
months: [],
days: [],
halfs: [{
label: '上午',
value: 1
}, {
label: '下午',
value: 2
}],
valueArr: [],
yearKey: 0,
monthKey: 0,
dayKey: 0,
halfKey: 0,
date: '',
startDate: '',
endDate: '',
time: {},
end_time: {},
tabs: ['月份选择', '自定义'],
tabIndex: 0,
opIndex: -1,
op1Index: 0,
options: ['近一个月', '近三个月', '近半年', '近一年', '近两年'],
fmt: 'yyyy-mm-dd',
isClick: false,
}
},
mounted() {
this.init();
},
watch: {
'time.year'(val, oval) {
if (this.params.month && oval) {
this.setMonths()
// this.setDays()
}
if (this.params.day && oval) {
this.setDays()
}
},
'time.month'(val, oval) {
if (this.params.day && oval) {
this.setDays()
}
},
},
methods: {
init() {
this.valueArr = [];
this.tabIndex = this.mode == 'multiple' ? 1 : 0
// 初始化默认选中时间
this.time = this.initTimeValue(this.defaultTime);
// 初始化截止时间
this.end_time = this.initTimeValue(this.endTime);
let fmt = []
if (this.optionMode == 'day') {
this.options = ['近3天', '近7天', '近15天']
}
if (this.params.year) {
this.valueArr.push(0);
this.yearKey = this.valueArr.length - 1
this.setYears();
fmt.push('yyyy')
fmt.push('-')
}
if (this.params.month) {
this.valueArr.push(0);
this.monthKey = this.valueArr.length - 1
this.setMonths();
fmt.push('mm')
fmt.push('-')
}
if (this.params.day) {
this.valueArr.push(0);
this.dayKey = this.valueArr.length - 1
this.setDays();
fmt.push('dd')
}
if (this.params.half) {
this.valueArr.push(0);
this.halfKey = this.valueArr.length - 1
}
this.fmt = fmt.join('')
// 根据需求做的数据处理
let currentDate = new Date();
if (this.successStartTime || this.successEndTime) {
if (this.tabIndex == 0) {
this.date = this.timeFormat(new Date(this.defaultTime.replace(/\-/g, '/')), this.fmt)
} else {
this.startDate = this.changeDateFmt(this.successStartTime);
this.date = this.endDate = this.changeDateFmt(this.successEndTime);
}
} else {
// 开始时间为一个月的月初
currentDate.setDate(1);
this.startDate = this.timeFormat(currentDate, this.fmt);
this.date = this.endDate = this.timeFormat(new Date(this.defaultTime.replace(/\-/g, '/')), this.fmt)
}
this.optionChange(0);
},
initDate() {
if (this.params.year) {
this.setYears();
}
if (this.params.month) {
this.setMonths();
}
if (this.params.day) {
this.setDays();
}
},
open() {
// this.$refs.popup.open('bottom')
},
close() {
uni.showLoading({
title: '加载中'
});
this.$emit('close');
// this.$refs.popup.close()
},
//点击重置
reset() {
this.close();
this.init()
this.$emit('reset');
},
// 点击确定
getResult() {
let result = {};
let {
date,
time,
halfs,
halfKey,
valueArr
} = this
if (this.tabIndex) {
let change_date = this.endDate
let start_time = {}
let end_time = {}
if (this.changeDateT(this.startDate) > this.changeDateT(this.endDate)) {
this.endDate = this.startDate
this.startDate = change_date
this.optionChange(0)
}
if (this.params.year) {
start_time.year = this.formatNumber(this.initTimeValue(this.startDate).year || 0);
end_time.year = this.formatNumber(this.initTimeValue(this.endDate).year || 0);
}
if (this.params.month) {
start_time.month = this.formatNumber(this.initTimeValue(this.startDate).month || 0);
end_time.month = this.formatNumber(this.initTimeValue(this.endDate).month || 0);
}
if (this.params.day) {
start_time.day = this.formatNumber(this.initTimeValue(this.startDate).day || 0);
end_time.day = this.formatNumber(this.initTimeValue(this.endDate).day || 0);
}
start_time.time = this.changeDateG(this.startDate);
end_time.time = this.changeDateG(this.endDate);
start_time.timestamp = new Date(this.changeDateT(this.startDate)).getTime();
end_time.timestamp = new Date(this.changeDateT(this.endDate)).getTime();
result = {
start_time,
end_time
}
} else {
if (this.params.year) result.year = this.formatNumber(time.year || 0);
if (this.params.month) result.month = this.formatNumber(time.month || 0);
if (this.params.day) result.day = this.formatNumber(time.day || 0);
result.time = date.substring(0, 7)
// result.half = halfs[valueArr[halfKey]].value
result.timestamp = new Date(this.changeDateT(date)).getTime();
}
console.log(result, 'result')
this.$emit('confirm', result);
this.close();
},
// 设置picker的某一列值
setYears() {
let {
time,
end_time
} = this
let {
year
} = end_time
// 获取年份集合
this.years = this.generateArray(2014, year);
// 设置this.valueArr某一项的值,是为了让picker预选中某一个值
setTimeout(() => {
this.valueArr.splice(this.yearKey, 1, this.getIndex(this.years, time.year));
}, 10)
},
setMonths() {
let {
time,
end_time
} = this
let {
year,
month
} = end_time
if (year == time.year && this.params.year) {
this.months = this.generateArray(1, month);
} else {
this.months = this.generateArray(1, 12);
}
if (time.month > this.months.length) this.time.month = this.months.length;
//解决微信小程序初始化问题
setTimeout(() => {
this.valueArr.splice(this.monthKey, 1, this.getIndex(this.months, time.month));
}, 10)
},
setDays() {
let {
time,
end_time
} = this
let {
year,
month,
day
} = end_time
let totalDays = new Date(time.year, time.month, 0).getDate();
if (year == time.year && month == time.month && this.params.year) {
this.days = this.generateArray(1, day);
} else {
this.days = this.generateArray(1, totalDays);
}
if (time.day > this.days.length) this.time.day = this.days.length;
setTimeout(() => {
this.valueArr.splice(this.dayKey, 1, this.getIndex(this.days, time.day));
}, 10)
},
// 生成递进的数组
generateArray: function(start, end) {
// 转为数值格式,否则用户给end-year等传递字符串值时,下面的end+1会导致字符串拼接,而不是相加
start = Number(start);
end = Number(end);
end = end > start ? end : start;
// 生成数组,获取其中的索引,并剪出来
return [...Array(end + 1).keys()].slice(start);
},
getIndex: function(arr, val) {
let index = arr.indexOf(val);
// 如果index为-1(即找不到index值),~(-1)=-(-1)-1=0,导致条件不成立
return ~index ? index : 0;
},
//日期时间处理
initTimeValue(defaultTime) {
defaultTime = this.changeDateT(defaultTime);
// 格式化时间,在IE浏览器(uni不存在此情况),无法识别日期间的"-"间隔符号
let fdate = defaultTime.replace(/\-/g, '/');
fdate = fdate && fdate.indexOf('/') == -1 ? `2020/01/01 ${fdate}` : fdate;
let time = null;
if (fdate) time = new Date(fdate);
else time = new Date();
// 获取年日月时分秒
return {
year: time.getFullYear(),
month: Number(time.getMonth()) + 1,
day: time.getDate(),
}
},
// 小于10前面补0,用于月份,日期,时分秒等
formatNumber(num) {
return +num < 10 ? '0' + num : String(num);
},
// 获取时间戳
getTimestamp(date) {
// yyyy-mm-dd为安卓写法,不支持iOS,需要使用"/"分隔,才能二者兼容
let time = date.year + '/' + date.month + '/' + (date.day || '01');
return new Date(time).getTime();
},
touchend(e) {
this.opIndex = -1
},
// 用户更改picker的列选项
change(e) {
this.valueArr = e.detail.value;
let i = 0;
let time = {
year: 0,
month: 0,
day: 0,
}
if (this.params.year) time.year = this.years[this.valueArr[i++]];
if (this.params.month) time.month = this.months[this.valueArr[i++]];
if (this.params.day) time.day = this.days[this.valueArr[i++]];
this.time = time
let date = this.timeFormat(this.getTimestamp(time), this.fmt)
//自定义时间段
if (this.tabIndex) {
if (this.op1Index) {
this.endDate = date;
} else {
this.startDate = date;
}
} else { //月份选择
this.date = date;
}
},
tabChange(i) {
this.tabIndex = i
if (!i) {
this.time = this.initTimeValue(this.date);
this.date = this.timeFormat(new Date(this.defaultTime.replace(/\-/g, '/')), this.fmt)
this.initDate()
} else {
let currentDate = new Date();
currentDate.setDate(1);
this.startDate = this.timeFormat(currentDate, this.fmt);
this.date = this.endDate = this.timeFormat(new Date(this.defaultTime.replace(/\-/g, '/')), this.fmt);
this.optionChange(0)
}
},
//选择快捷时间段
optionSelect(i) {
this.opIndex = i;
let end_time = new Date(); // 当前日期作为结束日期
let start_time;
switch (i) {
case 0: // 近一个月
start_time = new Date(end_time);
start_time.setMonth(end_time.getMonth() - 1); // 设置月份为前一个月
break;
case 1: // 近三天 或 近三个月
if (this.optionMode === 'day') {
start_time = new Date(end_time);
start_time.setDate(end_time.getDate() - 3); // 近三天
} else {
start_time = new Date(end_time);
start_time.setMonth(end_time.getMonth() - 3); // 近三个月
}
break;
case 2: // 近七天 或 近六个月(注意:原始代码是近半年,但通常半年为6个月)
if (this.optionMode === 'day') {
start_time = new Date(end_time);
start_time.setDate(end_time.getDate() - 7); // 近七天
} else {
start_time = new Date(end_time);
start_time.setMonth(end_time.getMonth() - 6); // 近六个月
}
break;
case 3: // 近十五天 或 近一年
if (this.optionMode === 'day') {
start_time = new Date(end_time);
start_time.setDate(end_time.getDate() - 15); // 近十五天
} else {
start_time = new Date(end_time);
start_time.setFullYear(end_time.getFullYear() - 1); // 近一年
}
break;
case 4: // 近两年
start_time = new Date(end_time);
start_time.setFullYear(end_time.getFullYear() - 2); // 近两年
break;
}
// 格式化日期并赋值给startDate和endDate
this.endDate = this.timeFormat(end_time, this.fmt);
this.startDate = this.timeFormat(start_time, this.fmt);
this.time = this.initTimeValue(this.startDate);
// 初始化日期或其他相关操作
this.initDate();
this.getResult()
},
//起始时间、截至时间切换
optionChange(i) {
this.op1Index = i
this.time = this.initTimeValue(i ? this.endDate : this.startDate);
this.initDate()
},
changeDateFmt(dateT) {
let s = dateT.split("-");
return s[0] + "年" + s[1] + "月" + s[2] + "日";
},
changeDateT(dateT) {
let s = dateT.replace(/[年,月,日]/g, '/').substring(0, 10);
return s;
},
changeDateG(dateT) {
let s = dateT.replace(/[年,月,日]/g, '-').substring(0, 10);
return s;
},
}
}
</script>
<style lang="scss" scoped>
.flex {
display: flex;
flex-direction: row;
align-items: center;
}
.row-between {
justify-content: space-between;
}
.popup-box {
background-color: #fff;
padding: 0 0 20rpx 0;
}
.picker-body {
overflow: hidden;
margin: 0 70rpx;
padding: 40rpx 0;
}
.picker-view {
height: 280rpx;
}
.column-item {
font-size: 30rpx;
color: black;
font-weight: 400;
}
.column-item-text {
line-height: 38px;
height: 38px;
font-size: 32rpx;
}
.title {
display: flex;
align-items: center;
justify-content: space-between;
flex-direction: row;
position: relative;
.close {
position: relative;
right: 50rpx;
}
.title-text {
width: 750rpx;
padding: 24rpx 0;
display: flex;
flex-direction: row;
justify-content: center;
.text {
font-size: 32rpx;
font-weight: 600;
}
}
}
.tabs-box {
width: 100%;
display: flex;
flex-direction: row;
.tabs-item:nth-child(2) {
padding: 0 0 10rpx 98rpx;
}
.tabs-item:nth-child(1) {
padding: 0 0 10rpx 50rpx;
}
.item-text {
color: #2C2C2C;
font-size: 24rpx;
font-weight: 500;
}
}
.tabs-check {
// border-bottom: 4rpx solid #1DAA9F !important;
.item-text {
color: #116C40;
font-size: 24rpx;
font-weight: 400;
}
}
.bottom {
padding: 0 32rpx 32rpx;
display: flex;
align-items: center;
flex-direction: row;
.h-btn {
flex: 1;
}
.resetClear {
width: 166px;
height: 42px;
line-height: 42px;
border-radius: 22px;
border: 1px solid black;
font-weight: 400;
font-size: 16px;
color: black;
text-align: center;
margin-right: 10px;
}
.confirm {
width: 166px;
height: 42px;
line-height: 42px;
background: linear-gradient(96deg, #4375D8 0%, #85B9FF 100%);
border-radius: 22px;
font-weight: 400;
font-size: 16px;
color: #FFFFFF;
text-align: center;
}
}
.option {
padding: 14rpx 58rpx;
font-size: 24rpx;
border-radius: 16rpx;
background: #F6F5FA;
display: flex;
justify-content: center;
flex-direction: row;
.option-text {
font-size: 24rpx;
font-weight: 500;
color: #333333;
line-height: 40rpx;
}
}
.timeStyle {
min-width: 190rpx;
height: 64rpx;
line-height: 64rpx;
background: #F7F6FB;
border-radius: 16rpx;
font-weight: 500;
font-size: 24rpx;
color: #333333;
text-align: center;
font-style: normal;
text-transform: none;
margin: 0 28rpx 28rpx 0;
letter-spacing: 1px;
}
.timeStyle2 {
position: relative;
min-width: 190rpx;
height: 64rpx;
line-height: 64rpx;
background: #E6F1EB;
border-radius: 16rpx;
font-weight: 500;
font-size: 24rpx;
color: #333333;
text-align: center;
font-style: normal;
text-transform: none;
margin: 0 28rpx 28rpx 0;
&:after {
content: '';
position: absolute;
right: -1px;
bottom: -1px;
width: 17.92px;
height: 19.21px;
background-image: url('@/static/images/2024050921.png');
background-size: cover;
}
}
.option-check {
background: #E6F1EB;
border-radius: 16rpx;
.option-text {
color: #2E7356;
}
}
.options-box {
padding: 0 40rpx 20rpx 40rpx;
transition-property: height;
transition-duration: .4s;
}
.time-container {
display: flex;
flex-wrap: wrap;
}
</style>
实现效果如下:
总结
做的时候用到了几种处理数据的方法 分享给大家:
// 将时间转成对应的星期
getWeekday(dateString) {
const date = new Date(dateString);
const weekday = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
return weekday[date.getDay()];
},
// 处理年月日的格式 this.formatDate(时间, '想要传入的符号')
formatDate(date, separator) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}${separator}${month}${separator}${day}`;
},
changeDateFmt(dateT) {
let s = dateT.split("-");
return s[0] + "年" + s[1] + "月" + s[2] + "日";
},
changeDateT(dateT) {
let s = dateT.replace(/[年,月,日]/g, '/').substring(0, 10);
return s;
},
changeDateG(dateT) {
let s = dateT.replace(/[年,月,日]/g, '-').substring(0, 10);
return s;
}