This commit is contained in:
aihe 2024-06-20 19:11:43 +08:00
parent ac33e7f2c5
commit d9ee6678d5
11 changed files with 645 additions and 542 deletions

View File

@ -0,0 +1,121 @@
<template>
<view class="page container">
<uni-card :is-shadow="false" is-full>
<text class="uni-h6">可以同时选择日期和时间的选择器</text>
</uni-card>
<uni-section :title="'日期用法:' + dateString" type="line"></uni-section>
<view class="example-body">
<uni-datetime-picker type="date" :clear-icon="false" v-model="dateString" @maskClick="maskClick" />
</view>
<uni-section :title="'日期时间用法:' + datetimeString" type="line"></uni-section>
<view class="example-body">
<uni-datetime-picker type="datetime" :start="start" :end="end" v-model="datetimeString" @change="change" />
</view>
<uni-section :title="'日期时间 default-value:' + datetimeDefaultValueString" type="line"></uni-section>
<view class="example-body">
<uni-datetime-picker type="datetime" :start="start" :end="end" :default-value="datetimeDefaultValue" v-model="datetimeDefaultValueString" @change="change" />
</view>
<uni-section :title="'日期范围用法:' + '[' + dateRange + ']'" type="line"></uni-section>
<view class="example-body">
<uni-datetime-picker v-model="dateRange" type="daterange" @maskClick="maskClick" />
</view>
<uni-section :title="'日期时间范围用法:' + '[' + datetimeRange + ']' " type="line"></uni-section>
<view class="example-body">
<uni-datetime-picker v-model="datetimeRange" type="datetimerange" rangeSeparator="至" />
</view>
<uni-section :title="'时间戳用法:' + dateTimestamp" type="line"></uni-section>
<view class="example-body">
<uni-datetime-picker returnType="timestamp" v-model="dateTimestamp" @change="change" />
</view>
<uni-section :title="'date 对象用法:' + dateInstance" type="line"></uni-section>
<view class="example-body">
<uni-datetime-picker type="datetime" returnType="date" v-model="dateInstance" @change="change" />
</view>
<uni-section :title="'插槽用法:' + dateString" type="line"></uni-section>
<view class="example-body">
<uni-datetime-picker v-model="dateString">我是一个插槽,点击我</uni-datetime-picker>
</view>
<uni-section :title="'无边框用法:' + dateString" type="line"></uni-section>
<view class="example-body">
<uni-datetime-picker v-model="dateString" :border="false" />
</view>
<uni-section :title="'隐藏清除按钮用法:' + dateString" type="line"></uni-section>
<view class="example-body">
<uni-datetime-picker v-model="dateString" :clearIcon="false" />
</view>
<uni-section :title="'disabled用法:' + dateString" type="line"></uni-section>
<view class="example-body">
<uni-datetime-picker v-model="dateString" disabled />
</view>
</view>
</template>
<script>
export default {
data() {
return {
dateString: this.getDateTime(new Date()),
datetimeString: this.getDateTime(new Date(), false),
datetimeDefaultValueString: '',
datetimeDefaultValue: this.getDateTime(Date.now() + 1 * 24 * 3600000),
dateTimestamp: Date.now(),
dateInstance: new Date(),
dateRange: [this.getDate(Date.now() - 5 * 24 * 3600000), this.getDate(Date.now() + 5 * 24 * 3600000)],
datetimeRange: [this.getDateTime(Date.now() - 5 * 24 * 3600000), this.getDateTime(Date.now() + 5 * 24 * 3600000)],
start: Date.now() - 10 * 24 * 3600000,
end: Date.now() + 10 * 24 * 3600000
}
},
watch: {
datetimeString() {
console.log('日期时间单选:', this.datetimeString);
},
dateRange() {
console.log('日期范围选:', this.dateRange);
},
datetimeRange() {
console.log('日期时间范围选:', this.datetimeRange);
}
},
methods: {
change(e) {
console.log('----change事件:', e);
},
maskClick() {
console.log('----maskClick事件');
},
getDateTime(date, addZero = true){
return `${this.getDate(date, addZero)} ${this.getTime(date, addZero)}`
},
getDate(date, addZero = true){
date = new Date(date)
const year = date.getFullYear()
const month = date.getMonth()+1
const day = date.getDate()
return `${year}-${addZero ? this.addZero(month) : month}-${addZero ? this.addZero(day) : day}`
},
getTime(date, addZero = true){
date = new Date(date)
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return this.hideSecond ?
`${addZero ? this.addZero(hour) : hour}:${addZero ? this.addZero(minute) : minute}` :
`${addZero ? this.addZero(hour) : hour}:${addZero ? this.addZero(minute) : minute}:${addZero ? this.addZero(second) : second}`
},
addZero(num) {
if (num < 10) {
num = `0${num}`
}
return num
}
}
}
</script>
<style lang="scss">
.example-body {
background-color: #fff;
padding: 10px;
}
</style>

View File

@ -9,7 +9,7 @@
</template> </template>
</u-input> </u-input>
<view class="pos-abt-all"> <view class="pos-abt-all">
<view v-if="showTools" @click.stop=""> <view v-if="showRangeTools" @click.stop="">
<tpx-select :list="toolsRangesList" v-model:value="rangeVal" mode="drop" @onChange="handleToolsRangChange"> <tpx-select :list="toolsRangesList" v-model:value="rangeVal" mode="drop" @onChange="handleToolsRangChange">
<view :style="`height: 64rpx;`" ></view> <view :style="`height: 64rpx;`" ></view>
</tpx-select> </tpx-select>
@ -18,19 +18,33 @@
</view> </view>
<!-- 日历 --> <!-- 日历 -->
<view v-if="showCladar"> <view v-if="showCladar">
<u-calendar title="请选择日期范围" :minDate="minDate" :monthNum="monthNum" color="#B12D29" :mode="mode" rowHeight="90" closeOnClickOverlay :show="showCladar" :defaultDate="value" @confirm="handleClaOk" @close="handleSwitchCladar" <uni-datetime-picker ref="unDateTimePckRef" @maskClick="handleClaClose"
></u-calendar> :start="minDate" :end="maxDate" v-model="proxyValue"
:type="mode" @change="handleClaValChange"
:placeholder="placeholder"
>
<!-- 使用自定义显示 -->
<view></view>
</uni-datetime-picker>
</view> </view>
</template> </template>
<script> <script>
import { } from "@/common/untool" // uni-datetime-picker 插件地址: https://ext.dcloud.net.cn/plugin?id=3962
import dayjs from "dayjs" import dayjs from "dayjs"
const formatStr = 'YYYY-MM-DD' const formatStr = 'YYYY-MM-DD'
export default { export default {
computed: { computed: {
proxyValue: {
get() {
return this.value
}
},
showRangeTools(){
return this.mode?.indexOf("range") > -1 && this.showTools
},
inputValue() { inputValue() {
let val = this.value let val = this.value
if(Array.isArray(val)) { if(Array.isArray(val)) {
@ -42,7 +56,11 @@
val[1] = dayjs(val[1]).format(formatStr) val[1] = dayjs(val[1]).format(formatStr)
} }
} }
return val && (val.length > 1 ? val.join("~") : val[0]) // 范围是数组,单个是字符串
if(this.mode?.indexOf("range") > -1) {
val = val && (val.length > 1 ? val.join("~") : val[0])
}
return val
}, },
}, },
props: { props: {
@ -58,7 +76,7 @@
}, },
fontSize: { fontSize: {
default () { default () {
return 26 return 28
} }
}, },
minDate: { minDate: {
@ -66,14 +84,14 @@
return dayjs().subtract(12, 'months').format(`${formatStr}`) return dayjs().subtract(12, 'months').format(`${formatStr}`)
} }
}, },
monthNum: { maxDate: {
default() { default() {
return 24 return dayjs().add(12, 'months').format(`${formatStr}`)
} }
}, },
mode: { mode: {
default() { default() {
return 'range' // single | multiple | range return 'daterange' // datetime | date | datetimerange | daterange
} }
}, },
customStyle:{ customStyle:{
@ -124,26 +142,39 @@
this.handleSwitchCladar() this.handleSwitchCladar()
}, },
handleChange(val){ handleChange(val){
val[0] = dayjs(val[0]).format(`${formatStr} 00:00:00`) if(Array.isArray(val)) {
val[1] = dayjs(val[1]).format(`${formatStr} 23:59:59`) // 补全 时间戳
if(val[0].indexOf(":") == -1) {
val[0] = dayjs(val[0]).format(`${formatStr} 00:00:00`)
}
if(val[1].indexOf(":") == -1) {
val[1] = dayjs(val[1]).format(`${formatStr} 23:59:59`)
}
}
this.$emit('change', val) this.$emit('change', val)
this.$emit('update:value', val) this.$emit('update:value', val)
}, },
handleClaOk(res){ handleClaValChange(val) {
const ary = Object.values(res)
const val = [ary[0], ary[ary.length-1]]
this.handleChange(val) this.handleChange(val)
},
handleClaClose(res){
this.handleSwitchCladar() this.handleSwitchCladar()
}, },
handleSwitchCladar() { handleSwitchCladar() {
this.showCladar = !this.showCladar this.showCladar = !this.showCladar
// 手动唤起日期事件
setTimeout(()=> {
if(this.showCladar) {
this.$refs.unDateTimePckRef.show()
}
}, 300)
}, },
handleToolsRangChange(val) { handleToolsRangChange(val) {
if(val == -1) { if(val == -1) {
this.handleSwitchCladar() this.handleSwitchCladar()
} else { } else {
let sltRang = this.toolsRangesList.filter(t=> t.val == val)[0].range let sltRang = this.toolsRangesList.filter(t=> t.val == val)[0].range
this.handleChange(sltRang) this.handleChange(sltRang, )
} }
} }
} }

View File

@ -1,3 +1,22 @@
## 2.2.25(2023-10-18)
- 修复 PC端初次修改时间,开始时间未更新的Bug [详情](https://github.com/dcloudio/uni-ui/issues/737)
## 2.2.24(2023-06-02)
- 修复 部分情况修改时间,开始、结束时间显示异常的Bug [详情](https://ask.dcloud.net.cn/question/171146)
- 优化 当前月可以选择上月、下月的日期的Bug
## 2.2.23(2023-05-02)
- 修复 部分情况修改时间,开始时间未更新的Bug [详情](https://github.com/dcloudio/uni-ui/issues/737)
- 修复 部分平台及设备第一次点击无法显示弹框的Bug
- 修复 ios 日期格式未补零显示及使用异常的Bug [详情](https://ask.dcloud.net.cn/question/162979)
## 2.2.22(2023-03-30)
- 修复 日历 picker 修改年月后,自动选中当月1日的Bug [详情](https://ask.dcloud.net.cn/question/165937)
- 修复 小程序端 低版本 ios NaN的Bug [详情](https://ask.dcloud.net.cn/question/162979)
## 2.2.21(2023-02-20)
- 修复 firefox 浏览器显示区域点击无法拉起日历弹框的Bug [详情](https://ask.dcloud.net.cn/question/163362)
## 2.2.20(2023-02-17)
- 优化 值为空依然选中当天问题
- 优化 提供 default-value 属性支持配置选择器打开时默认显示的时间
- 优化 非范围选择未选择日期时间,点击确认按钮选中当前日期时间
- 优化 字节小程序日期时间范围选择,底部日期换行的Bug
## 2.2.19(2023-02-09) ## 2.2.19(2023-02-09)
- 修复 2.2.18 引起范围选择配置 end 选择无效的Bug [详情](https://github.com/dcloudio/uni-ui/issues/686) - 修复 2.2.18 引起范围选择配置 end 选择无效的Bug [详情](https://github.com/dcloudio/uni-ui/issues/686)
## 2.2.18(2023-02-08) ## 2.2.18(2023-02-08)

View File

@ -13,10 +13,10 @@
'uni-calendar-item--after-checked':weeks.afterMultiple, 'uni-calendar-item--after-checked':weeks.afterMultiple,
'uni-calendar-item--disable':weeks.disable, 'uni-calendar-item--disable':weeks.disable,
}"> }">
<text v-if="selected&&weeks.extraInfo" class="uni-calendar-item__weeks-box-circle"></text> <text v-if="selected && weeks.extraInfo" class="uni-calendar-item__weeks-box-circle"></text>
<text class="uni-calendar-item__weeks-box-text uni-calendar-item__weeks-box-text-disable uni-calendar-item--checked-text">{{weeks.date}}</text> <text class="uni-calendar-item__weeks-box-text uni-calendar-item__weeks-box-text-disable uni-calendar-item--checked-text">{{weeks.date}}</text>
</view> </view>
<view :class="{'uni-calendar-item--isDay': weeks.isDay}"></view> <view :class="{'uni-calendar-item--today': weeks.isToday}"></view>
</view> </view>
</template> </template>
@ -41,10 +41,6 @@
return [] return []
} }
}, },
lunar: {
type: Boolean,
default: false
},
checkHover: { checkHover: {
type: Boolean, type: Boolean,
default: false default: false
@ -83,11 +79,6 @@
color: darken($color: $uni-primary, $amount: 40%); color: darken($color: $uni-primary, $amount: 40%);
} }
.uni-calendar-item__weeks-lunar-text {
font-size: 12px;
color: #333;
}
.uni-calendar-item__weeks-box-item { .uni-calendar-item__weeks-box-item {
position: relative; position: relative;
/* #ifndef APP-NVUE */ /* #ifndef APP-NVUE */
@ -123,7 +114,7 @@
color: #D1D1D1; color: #D1D1D1;
} }
.uni-calendar-item--isDay { .uni-calendar-item--today {
position: absolute; position: absolute;
top: 10px; top: 10px;
right: 17%; right: 17%;

View File

@ -1,29 +1,37 @@
<template> <template>
<view class="uni-calendar" @mouseleave="leaveCale"> <view class="uni-calendar" @mouseleave="leaveCale">
<view v-if="!insert&&show" class="uni-calendar__mask" :class="{'uni-calendar--mask-show':aniMaskShow}"
@click="clean();maskClick()"></view> <view v-if="!insert && show" class="uni-calendar__mask" :class="{'uni-calendar--mask-show':aniMaskShow}"
@click="maskClick"></view>
<view v-if="insert || show" class="uni-calendar__content" <view v-if="insert || show" class="uni-calendar__content"
:class="{'uni-calendar--fixed':!insert,'uni-calendar--ani-show':aniMaskShow, 'uni-calendar__content-mobile': aniMaskShow}"> :class="{'uni-calendar--fixed':!insert,'uni-calendar--ani-show':aniMaskShow, 'uni-calendar__content-mobile': aniMaskShow}">
<view class="uni-calendar__header" :class="{'uni-calendar__header-mobile' :!insert}"> <view class="uni-calendar__header" :class="{'uni-calendar__header-mobile' :!insert}">
<view v-if="left" class="uni-calendar__header-btn-box" @click.stop="pre">
<view class="uni-calendar__header-btn-box" @click.stop="changeMonth('pre')">
<view class="uni-calendar__header-btn uni-calendar--left"></view> <view class="uni-calendar__header-btn uni-calendar--left"></view>
</view> </view>
<picker mode="date" :value="date" fields="month" @change="bindDateChange"> <picker mode="date" :value="date" fields="month" @change="bindDateChange">
<text <text
class="uni-calendar__header-text">{{ (nowDate.year||'') + yearText + ( nowDate.month||'') + monthText}}</text> class="uni-calendar__header-text">{{ (nowDate.year||'') + yearText + ( nowDate.month||'') + monthText}}</text>
</picker> </picker>
<view v-if="right" class="uni-calendar__header-btn-box" @click.stop="next">
<view class="uni-calendar__header-btn-box" @click.stop="changeMonth('next')">
<view class="uni-calendar__header-btn uni-calendar--right"></view> <view class="uni-calendar__header-btn uni-calendar--right"></view>
</view> </view>
<view v-if="!insert" class="dialog-close" @click="clean">
<view v-if="!insert" class="dialog-close" @click="close">
<view class="dialog-close-plus" data-id="close"></view> <view class="dialog-close-plus" data-id="close"></view>
<view class="dialog-close-plus dialog-close-rotate" data-id="close"></view> <view class="dialog-close-plus dialog-close-rotate" data-id="close"></view>
</view> </view>
</view> </view>
<view class="uni-calendar__box"> <view class="uni-calendar__box">
<view v-if="showMonth" class="uni-calendar__box-bg"> <view v-if="showMonth" class="uni-calendar__box-bg">
<text class="uni-calendar__box-bg-text">{{nowDate.month}}</text> <text class="uni-calendar__box-bg-text">{{nowDate.month}}</text>
</view> </view>
<view class="uni-calendar__weeks" style="padding-bottom: 7px;"> <view class="uni-calendar__weeks" style="padding-bottom: 7px;">
<view class="uni-calendar__weeks-day"> <view class="uni-calendar__weeks-day">
<text class="uni-calendar__weeks-day-text">{{SUNText}}</text> <text class="uni-calendar__weeks-day-text">{{SUNText}}</text>
@ -47,28 +55,30 @@
<text class="uni-calendar__weeks-day-text">{{SATText}}</text> <text class="uni-calendar__weeks-day-text">{{SATText}}</text>
</view> </view>
</view> </view>
<view class="uni-calendar__weeks" v-for="(item,weekIndex) in weeks" :key="weekIndex"> <view class="uni-calendar__weeks" v-for="(item,weekIndex) in weeks" :key="weekIndex">
<view class="uni-calendar__weeks-item" v-for="(weeks,weeksIndex) in item" :key="weeksIndex"> <view class="uni-calendar__weeks-item" v-for="(weeks,weeksIndex) in item" :key="weeksIndex">
<calendar-item class="uni-calendar-item--hook" :weeks="weeks" :calendar="calendar" <calendar-item class="uni-calendar-item--hook" :weeks="weeks" :calendar="calendar"
:selected="selected" :lunar="lunar" :checkHover="range" @change="choiceDate" :selected="selected" :checkHover="range" @change="choiceDate"
@handleMouse="handleMouse"> @handleMouse="handleMouse">
</calendar-item> </calendar-item>
</view> </view>
</view> </view>
</view> </view>
<view v-if="!insert && !range && typeHasTime" class="uni-date-changed uni-calendar--fixed-top"
<view v-if="!insert && !range && hasTime" class="uni-date-changed uni-calendar--fixed-top"
style="padding: 0 80px;"> style="padding: 0 80px;">
<view class="uni-date-changed--time-date">{{tempSingleDate ? tempSingleDate : selectDateText}}</view> <view class="uni-date-changed--time-date">{{tempSingleDate ? tempSingleDate : selectDateText}}</view>
<time-picker type="time" :start="reactStartTime" :end="reactEndTime" v-model="time" <time-picker type="time" :start="timepickerStartTime" :end="timepickerEndTime" v-model="time"
:disabled="!tempSingleDate" :border="false" :hide-second="hideSecond" class="time-picker-style"> :disabled="!tempSingleDate" :border="false" :hide-second="hideSecond" class="time-picker-style">
</time-picker> </time-picker>
</view> </view>
<view v-if="!insert && range && typeHasTime" class="uni-date-changed uni-calendar--fixed-top"> <view v-if="!insert && range && hasTime" class="uni-date-changed uni-calendar--fixed-top">
<view class="uni-date-changed--time-start"> <view class="uni-date-changed--time-start">
<view class="uni-date-changed--time-date">{{tempRange.before ? tempRange.before : startDateText}} <view class="uni-date-changed--time-date">{{tempRange.before ? tempRange.before : startDateText}}
</view> </view>
<time-picker type="time" :start="reactStartTime" v-model="timeRange.startTime" :border="false" <time-picker type="time" :start="timepickerStartTime" v-model="timeRange.startTime" :border="false"
:hide-second="hideSecond" :disabled="!tempRange.before" class="time-picker-style"> :hide-second="hideSecond" :disabled="!tempRange.before" class="time-picker-style">
</time-picker> </time-picker>
</view> </view>
@ -77,11 +87,12 @@
</view> </view>
<view class="uni-date-changed--time-end"> <view class="uni-date-changed--time-end">
<view class="uni-date-changed--time-date">{{tempRange.after ? tempRange.after : endDateText}}</view> <view class="uni-date-changed--time-date">{{tempRange.after ? tempRange.after : endDateText}}</view>
<time-picker type="time" :end="reactEndTime" v-model="timeRange.endTime" :border="false" <time-picker type="time" :end="timepickerEndTime" v-model="timeRange.endTime" :border="false"
:hide-second="hideSecond" :disabled="!tempRange.after" class="time-picker-style"> :hide-second="hideSecond" :disabled="!tempRange.after" class="time-picker-style">
</time-picker> </time-picker>
</view> </view>
</view> </view>
<view v-if="!insert" class="uni-date-changed uni-date-btn--ok"> <view v-if="!insert" class="uni-date-changed uni-date-btn--ok">
<view class="uni-datetime-picker--btn" @click="confirm">{{confirmText}}</view> <view class="uni-datetime-picker--btn" @click="confirm">{{confirmText}}</view>
</view> </view>
@ -90,7 +101,7 @@
</template> </template>
<script> <script>
import Calendar from './util.js'; import { Calendar, getDate, getTime } from './util.js';
import calendarItem from './calendar-item.vue' import calendarItem from './calendar-item.vue'
import timePicker from './time-picker.vue' import timePicker from './time-picker.vue'
@ -103,7 +114,6 @@
* @description 日历组件可以查看日期,选择任意范围内的日期,打点操作。常用场景如:酒店日期预订、火车机票选择购买日期、上下班打卡等 * @description 日历组件可以查看日期,选择任意范围内的日期,打点操作。常用场景如:酒店日期预订、火车机票选择购买日期、上下班打卡等
* @tutorial https://ext.dcloud.net.cn/plugin?id=56 * @tutorial https://ext.dcloud.net.cn/plugin?id=56
* @property {String} date 自定义当前时间,默认为今天 * @property {String} date 自定义当前时间,默认为今天
* @property {Boolean} lunar 显示农历
* @property {String} startDate 日期选择范围-开始日期 * @property {String} startDate 日期选择范围-开始日期
* @property {String} endDate 日期选择范围-结束日期 * @property {String} endDate 日期选择范围-结束日期
* @property {Boolean} range 范围选择 * @property {Boolean} range 范围选择
@ -113,10 +123,11 @@
* @property {Boolean} clearDate = [true|false] 弹窗模式是否清空上次选择内容 * @property {Boolean} clearDate = [true|false] 弹窗模式是否清空上次选择内容
* @property {Array} selected 打点,期待格式[{date: '2019-06-27', info: '签到', data: { custom: '自定义信息', name: '自定义消息头',xxx:xxx... }}] * @property {Array} selected 打点,期待格式[{date: '2019-06-27', info: '签到', data: { custom: '自定义信息', name: '自定义消息头',xxx:xxx... }}]
* @property {Boolean} showMonth 是否选择月份为背景 * @property {Boolean} showMonth 是否选择月份为背景
* @property {[String} defaultValue 选择器打开时默认显示的时间
* @event {Function} change 日期改变,`insert :ture` 时生效 * @event {Function} change 日期改变,`insert :ture` 时生效
* @event {Function} confirm 确认选择`insert :false` 时生效 * @event {Function} confirm 确认选择`insert :false` 时生效
* @event {Function} monthSwitch 切换月份时触发 * @event {Function} monthSwitch 切换月份时触发
* @example <uni-calendar :insert="true":lunar="true" :start-date="'2019-3-2'":end-date="'2019-5-20'"@change="change" /> * @example <uni-calendar :insert="true" :start-date="'2019-3-2'":end-date="'2019-5-20'"@change="change" />
*/ */
export default { export default {
components: { components: {
@ -144,10 +155,6 @@
return [] return []
} }
}, },
lunar: {
type: Boolean,
default: false
},
startDate: { startDate: {
type: String, type: String,
default: '' default: ''
@ -168,7 +175,7 @@
type: Boolean, type: Boolean,
default: false default: false
}, },
typeHasTime: { hasTime: {
type: Boolean, type: Boolean,
default: false default: false
}, },
@ -184,14 +191,6 @@
type: Boolean, type: Boolean,
default: true default: true
}, },
left: {
type: Boolean,
default: true
},
right: {
type: Boolean,
default: true
},
checkHover: { checkHover: {
type: Boolean, type: Boolean,
default: true default: true
@ -210,14 +209,18 @@
fulldate: '' fulldate: ''
} }
} }
} },
defaultValue: {
type: [String, Object, Array],
default: ''
}
}, },
data() { data() {
return { return {
show: false, show: false,
weeks: [], weeks: [],
calendar: {}, calendar: {},
nowDate: '', nowDate: {},
aniMaskShow: false, aniMaskShow: false,
firstEnter: true, firstEnter: true,
time: '', time: '',
@ -260,7 +263,7 @@
if(!this.cale){ if(!this.cale){
return return
} }
this.cale.resetSatrtDate(val) this.cale.setStartDate(val)
this.cale.setDate(this.nowDate.fullDate) this.cale.setDate(this.nowDate.fullDate)
this.weeks = this.cale.weeks this.weeks = this.cale.weeks
}, },
@ -269,7 +272,7 @@
if(!this.cale){ if(!this.cale){
return return
} }
this.cale.resetEndDate(val) this.cale.setEndDate(val)
this.cale.setDate(this.nowDate.fullDate) this.cale.setDate(this.nowDate.fullDate)
this.weeks = this.cale.weeks this.weeks = this.cale.weeks
}, },
@ -312,10 +315,10 @@
} }
this.cale.setDefaultMultiple(before, after) this.cale.setDefaultMultiple(before, after)
if (which === 'left') { if (which === 'left' && before) {
this.setDate(before) this.setDate(before)
this.weeks = this.cale.weeks this.weeks = this.cale.weeks
} else { } else if(after) {
this.setDate(after) this.setDate(after)
this.weeks = this.cale.weeks this.weeks = this.cale.weeks
} }
@ -326,15 +329,13 @@
} }
}, },
computed: { computed: {
reactStartTime() { timepickerStartTime() {
const activeDate = this.range ? this.tempRange.before : this.calendar.fullDate const activeDate = this.range ? this.tempRange.before : this.calendar.fullDate
const res = activeDate === this.startDate ? this.selectableTimes.start : '' return activeDate === this.startDate ? this.selectableTimes.start : ''
return res
}, },
reactEndTime() { timepickerEndTime() {
const activeDate = this.range ? this.tempRange.after : this.calendar.fullDate const activeDate = this.range ? this.tempRange.after : this.calendar.fullDate
const res = activeDate === this.endDate ? this.selectableTimes.end : '' return activeDate === this.endDate ? this.selectableTimes.end : ''
return res
}, },
/** /**
* for i18n * for i18n
@ -420,14 +421,9 @@
const [yearB, monthB] = B.split('-') const [yearB, monthB] = B.split('-')
return yearA === yearB && monthA === monthB return yearA === yearB && monthA === monthB
}, },
// 取消穿透
clean() {
this.close()
},
// 蒙版点击事件 // 蒙版点击事件
maskClick() { maskClick() {
this.close()
this.$emit('maskClose') this.$emit('maskClose')
}, },
@ -446,21 +442,48 @@
this.tempSingleDate = '' this.tempSingleDate = ''
} }
this.calendar.fullDate = '' this.calendar.fullDate = ''
this.setDate() this.setDate(new Date())
}, },
bindDateChange(e) { bindDateChange(e) {
const value = e.detail.value + '-1' const value = e.detail.value + '-1'
this.init(value) this.setDate(value)
}, },
/** /**
* 初始化日期显示 * 初始化日期显示
* @param {Object} date * @param {Object} date
*/ */
init(date) { init(date) {
this.cale.setDate(date) // 字节小程序 watch 早于 created
if(!this.cale){
return
}
this.cale.setDate(date || new Date())
this.weeks = this.cale.weeks this.weeks = this.cale.weeks
this.nowDate = this.calendar = this.cale.getInfo(date) this.nowDate = this.cale.getInfo(date)
this.calendar = {...this.nowDate}
if(!date){
// 优化date为空默认不选中今天
this.calendar.fullDate = ''
if(this.defaultValue && !this.range){
// 暂时只支持移动端非范围选择
const defaultDate = new Date(this.defaultValue)
const fullDate = getDate(defaultDate)
const year = defaultDate.getFullYear()
const month = defaultDate.getMonth()+1
const date = defaultDate.getDate()
const day = defaultDate.getDay()
this.calendar = {
fullDate,
year,
month,
date,
day
},
this.tempSingleDate = fullDate
this.time = getTime(defaultDate, this.hideSecond)
}
}
}, },
/** /**
* 打开日历弹窗 * 打开日历弹窗
@ -469,7 +492,6 @@
// 弹窗模式并且清理数据 // 弹窗模式并且清理数据
if (this.clearDate && !this.insert) { if (this.clearDate && !this.insert) {
this.cale.cleanMultipleStatus() this.cale.cleanMultipleStatus()
// this.cale.setDate(this.date)
this.init(this.date) this.init(this.date)
} }
this.show = true this.show = true
@ -523,12 +545,20 @@
* @param {Object} name * @param {Object} name
*/ */
setEmit(name) { setEmit(name) {
if(!this.range){
if(!this.calendar.fullDate){
this.calendar = this.cale.getInfo(new Date())
this.tempSingleDate = this.calendar.fullDate
}
if(this.hasTime && !this.time) {
this.time = getTime(new Date(), this.hideSecond)
}
}
let { let {
year, year,
month, month,
date, date,
fullDate, fullDate,
lunar,
extraInfo extraInfo
} = this.calendar } = this.calendar
this.$emit(name, { this.$emit(name, {
@ -539,7 +569,6 @@
time: this.time, time: this.time,
timeRange: this.timeRange, timeRange: this.timeRange,
fulldate: fullDate, fulldate: fullDate,
lunar,
extraInfo: extraInfo || {} extraInfo: extraInfo || {}
}) })
}, },
@ -566,46 +595,17 @@
} }
this.change() this.change()
}, },
/** changeMonth(type) {
* 回到今天 let newDate
*/ if(type === 'pre') {
backtoday() { newDate = this.cale.getPreMonthObj(this.nowDate.fullDate).fullDate
let date = this.cale.getDate(new Date()).fullDate } else if(type === 'next') {
// this.cale.setDate(date) newDate = this.cale.getNextMonthObj(this.nowDate.fullDate).fullDate
this.init(date) }
this.change()
},
/**
* 比较时间大小
*/
dateCompare(startDate, endDate) {
// 计算截止时间
startDate = new Date(startDate.replace('-', '/').replace('-', '/'))
// 计算详细项的截止时间
endDate = new Date(endDate.replace('-', '/').replace('-', '/'))
if (startDate <= endDate) {
return true
} else {
return false
}
},
/**
* 上个月
*/
pre() {
const preDate = this.cale.getDate(this.nowDate.fullDate, -1, 'month').fullDate
this.setDate(preDate)
this.monthSwitch()
}, this.setDate(newDate)
/**
* 下个月
*/
next() {
const nextDate = this.cale.getDate(this.nowDate.fullDate, +1, 'month').fullDate
this.setDate(nextDate)
this.monthSwitch() this.monthSwitch()
}, },
/** /**
* 设置日期 * 设置日期
* @param {Object} date * @param {Object} date
@ -855,14 +855,17 @@
.uni-date-changed--time-end { .uni-date-changed--time-end {
/* #ifndef APP-NVUE */ /* #ifndef APP-NVUE */
display: flex; display: flex;
/* #endif */ /* #endif */
align-items: center; align-items: center;
} }
.uni-date-changed--time-date { .uni-date-changed--time-date {
color: #999; color: #999;
line-height: 50px; line-height: 50px;
/* #ifdef MP-TOUTIAO */
font-size: 16px;
/* #endif */
margin-right: 5px; margin-right: 5px;
// opacity: 0.6; // opacity: 0.6;
} }

View File

@ -1,7 +1,7 @@
{ {
"uni-datetime-picker.selectDate": "select date", "uni-datetime-picker.selectDate": "select date",
"uni-datetime-picker.selectTime": "select time", "uni-datetime-picker.selectTime": "select time",
"uni-datetime-picker.selectDateTime": "select datetime", "uni-datetime-picker.selectDateTime": "select date and time",
"uni-datetime-picker.startDate": "start date", "uni-datetime-picker.startDate": "start date",
"uni-datetime-picker.endDate": "end date", "uni-datetime-picker.endDate": "end date",
"uni-datetime-picker.startTime": "start time", "uni-datetime-picker.startTime": "start time",

View File

@ -2,7 +2,8 @@ import en from './en.json'
import zhHans from './zh-Hans.json' import zhHans from './zh-Hans.json'
import zhHant from './zh-Hant.json' import zhHant from './zh-Hant.json'
export default { export default {
en, // en,
en: zhHans, // TODO 先注释, 硬重置 中文 语言包顺序, 默认中文
'zh-Hans': zhHans, 'zh-Hans': zhHans,
'zh-Hant': zhHant 'zh-Hant': zhHant
} }

View File

@ -84,6 +84,7 @@
import { initVueI18n } from '@dcloudio/uni-i18n' import { initVueI18n } from '@dcloudio/uni-i18n'
import i18nMessages from './i18n/index.js' import i18nMessages from './i18n/index.js'
const { t } = initVueI18n(i18nMessages) const { t } = initVueI18n(i18nMessages)
import { fixIosDateFormat } from './util'
/** /**
* DatetimePicker 时间选择器 * DatetimePicker 时间选择器
@ -176,7 +177,7 @@
value: { value: {
handler(newVal) { handler(newVal) {
if (newVal) { if (newVal) {
this.parseValue(this.fixIosDateFormat(newVal)) //兼容 iOS、safari 日期格式 this.parseValue(fixIosDateFormat(newVal))
this.initTime(false) this.initTime(false)
} else { } else {
this.time = '' this.time = ''
@ -190,7 +191,7 @@
modelValue: { modelValue: {
handler(newVal) { handler(newVal) {
if (newVal) { if (newVal) {
this.parseValue(this.fixIosDateFormat(newVal)) //兼容 iOS、safari 日期格式 this.parseValue(fixIosDateFormat(newVal))
this.initTime(false) this.initTime(false)
} else { } else {
this.time = '' this.time = ''
@ -220,13 +221,13 @@
}, },
start: { start: {
handler(newVal) { handler(newVal) {
this.parseDatetimeRange(this.fixIosDateFormat(newVal), 'start') //兼容 iOS、safari 日期格式 this.parseDatetimeRange(fixIosDateFormat(newVal), 'start')
}, },
immediate: true immediate: true
}, },
end: { end: {
handler(newVal) { handler(newVal) {
this.parseDatetimeRange(this.fixIosDateFormat(newVal), 'end') //兼容 iOS、safari 日期格式 this.parseDatetimeRange(fixIosDateFormat(newVal), 'end')
}, },
immediate: true immediate: true
}, },
@ -739,7 +740,7 @@
*/ */
initTimePicker() { initTimePicker() {
if (this.disabled) return if (this.disabled) return
const value = this.fixIosDateFormat(this.time) const value = fixIosDateFormat(this.time)
this.initPickerValue(value) this.initPickerValue(value)
this.visible = !this.visible this.visible = !this.visible
}, },

View File

@ -8,19 +8,16 @@
> >
<view v-if="!isRange" class="uni-date-x uni-date-single"> <view v-if="!isRange" class="uni-date-x uni-date-single">
<uni-icons class="icon-calendar" type="calendar" color="#c0c4cc" size="22"></uni-icons> <uni-icons class="icon-calendar" type="calendar" color="#c0c4cc" size="22"></uni-icons>
<input class="uni-date__x-input" type="text" v-model="displayValue" <view class="uni-date__x-input">{{ displayValue || singlePlaceholderText }}</view>
:placeholder="singlePlaceholderText" :disabled="true" />
</view> </view>
<view v-else class="uni-date-x uni-date-range"> <view v-else class="uni-date-x uni-date-range">
<uni-icons class="icon-calendar" type="calendar" color="#c0c4cc" size="22"></uni-icons> <uni-icons class="icon-calendar" type="calendar" color="#c0c4cc" size="22"></uni-icons>
<input class="uni-date__x-input t-c" type="text" v-model="range.startDate" <view class="uni-date__x-input text-center">{{ displayRangeValue.startDate || startPlaceholderText }}</view>
:placeholder="startPlaceholderText" :disabled="true" />
<view class="range-separator">{{rangeSeparator}}</view> <view class="range-separator">{{rangeSeparator}}</view>
<input class="uni-date__x-input t-c" type="text" v-model="range.endDate" <view class="uni-date__x-input text-center">{{ displayRangeValue.endDate || endPlaceholderText }}</view>
:placeholder="endPlaceholderText" :disabled="true" />
</view> </view>
<view v-if="showClearIcon" class="uni-date__icon-clear" @click.stop="clear"> <view v-if="showClearIcon" class="uni-date__icon-clear" @click.stop="clear">
@ -33,37 +30,38 @@
<view v-show="pickerVisible" class="uni-date-mask--pc" @click="close"></view> <view v-show="pickerVisible" class="uni-date-mask--pc" @click="close"></view>
<view v-if="!isPhone" v-show="pickerVisible" ref="datePicker" class="uni-date-picker__container"> <view v-if="!isPhone" v-show="pickerVisible" ref="datePicker" class="uni-date-picker__container">
<view v-if="!isRange" class="uni-date-single--x" :style="popover"> <view v-if="!isRange" class="uni-date-single--x" :style="pickerPositionStyle">
<view class="uni-popper__arrow"></view> <view class="uni-popper__arrow"></view>
<view v-if="hasTime" class="uni-date-changed popup-x-header"> <view v-if="hasTime" class="uni-date-changed popup-x-header">
<input class="uni-date__input t-c" type="text" v-model="inputDate" <input class="uni-date__input text-center" type="text" v-model="inputDate"
:placeholder="selectDateText" /> :placeholder="selectDateText" />
<time-picker type="time" v-model="pickerTime" :border="false" :disabled="!inputDate" <time-picker type="time" v-model="pickerTime" :border="false" :disabled="!inputDate"
:start="reactStartTime" :end="reactEndTime" :hideSecond="hideSecond" style="width: 100%;"> :start="timepickerStartTime" :end="timepickerEndTime" :hideSecond="hideSecond" style="width: 100%;">
<input class="uni-date__input t-c" type="text" v-model="pickerTime" :placeholder="selectTimeText" <input class="uni-date__input text-center" type="text" v-model="pickerTime" :placeholder="selectTimeText"
:disabled="!inputDate" /> :disabled="!inputDate" />
</time-picker> </time-picker>
</view> </view>
<calendar ref="pcSingle" :showMonth="false" :start-date="caleRange.startDate" <Calendar ref="pcSingle" :showMonth="false" :start-date="calendarRange.startDate"
:end-date="caleRange.endDate" :date="calendarDate" @change="singleChange" :end-date="calendarRange.endDate" :date="calendarDate" @change="singleChange"
:default-value="defaultValue"
style="padding: 0 8px;" /> style="padding: 0 8px;" />
<view v-if="hasTime" class="popup-x-footer"> <view v-if="hasTime" class="popup-x-footer">
<text class="confirm" @click="confirmSingleChange">{{okText}}</text> <text class="confirm-text" @click="confirmSingleChange">{{okText}}</text>
</view> </view>
</view> </view>
<view v-else class="uni-date-range--x" :style="popover"> <view v-else class="uni-date-range--x" :style="pickerPositionStyle">
<view class="uni-popper__arrow"></view> <view class="uni-popper__arrow"></view>
<view v-if="hasTime" class="popup-x-header uni-date-changed"> <view v-if="hasTime" class="popup-x-header uni-date-changed">
<view class="popup-x-header--datetime"> <view class="popup-x-header--datetime">
<input class="uni-date__input uni-date-range__input" type="text" v-model="tempRange.startDate" <input class="uni-date__input uni-date-range__input" type="text" v-model="tempRange.startDate"
:placeholder="startDateText" /> :placeholder="startDateText" />
<time-picker type="time" v-model="tempRange.startTime" :start="reactStartTime" :border="false" <time-picker type="time" v-model="tempRange.startTime" :start="timepickerStartTime" :border="false"
:disabled="!tempRange.startDate" :hideSecond="hideSecond"> :disabled="!tempRange.startDate" :hideSecond="hideSecond">
<input class="uni-date__input uni-date-range__input" type="text" <input class="uni-date__input uni-date-range__input" type="text"
v-model="tempRange.startTime" :placeholder="startTimeText" v-model="tempRange.startTime" :placeholder="startTimeText"
@ -77,7 +75,7 @@
<input class="uni-date__input uni-date-range__input" type="text" v-model="tempRange.endDate" <input class="uni-date__input uni-date-range__input" type="text" v-model="tempRange.endDate"
:placeholder="endDateText" /> :placeholder="endDateText" />
<time-picker type="time" v-model="tempRange.endTime" :end="reactEndTime" :border="false" <time-picker type="time" v-model="tempRange.endTime" :end="timepickerEndTime" :border="false"
:disabled="!tempRange.endDate" :hideSecond="hideSecond"> :disabled="!tempRange.endDate" :hideSecond="hideSecond">
<input class="uni-date__input uni-date-range__input" type="text" v-model="tempRange.endTime" <input class="uni-date__input uni-date-range__input" type="text" v-model="tempRange.endTime"
:placeholder="endTimeText" :disabled="!tempRange.endDate" /> :placeholder="endTimeText" :disabled="!tempRange.endDate" />
@ -86,27 +84,28 @@
</view> </view>
<view class="popup-x-body"> <view class="popup-x-body">
<calendar ref="left" :showMonth="false" :start-date="caleRange.startDate" <Calendar ref="left" :showMonth="false" :start-date="calendarRange.startDate"
:end-date="caleRange.endDate" :range="true" @change="leftChange" :pleStatus="endMultipleStatus" :end-date="calendarRange.endDate" :range="true" :pleStatus="endMultipleStatus"
@firstEnterCale="updateRightCale" style="padding: 0 8px;" /> @change="leftChange" @firstEnterCale="updateRightCale" style="padding: 0 8px;" />
<calendar ref="right" :showMonth="false" :start-date="caleRange.startDate" <Calendar ref="right" :showMonth="false" :start-date="calendarRange.startDate"
:end-date="caleRange.endDate" :range="true" @change="rightChange" :end-date="calendarRange.endDate" :range="true" @change="rightChange"
:pleStatus="startMultipleStatus" @firstEnterCale="updateLeftCale" :pleStatus="startMultipleStatus" @firstEnterCale="updateLeftCale"
style="padding: 0 8px;border-left: 1px solid #F1F1F1;" /> style="padding: 0 8px;border-left: 1px solid #F1F1F1;" />
</view> </view>
<view v-if="hasTime" class="popup-x-footer"> <view v-if="hasTime" class="popup-x-footer">
<text class="" @click="clear">{{clearText}}</text> <text @click="clear">{{clearText}}</text>
<text class="confirm" @click="confirmRangeChange">{{okText}}</text> <text class="confirm-text" @click="confirmRangeChange">{{okText}}</text>
</view> </view>
</view> </view>
</view> </view>
<calendar v-if="isPhone" ref="mobile" :clearDate="false" :date="calendarDate" :defTime="reactMobDefTime" <Calendar v-if="isPhone" ref="mobile" :clearDate="false" :date="calendarDate" :defTime="mobileCalendarTime"
:start-date="caleRange.startDate" :end-date="caleRange.endDate" :selectableTimes="mobSelectableTime" :start-date="calendarRange.startDate" :end-date="calendarRange.endDate" :selectableTimes="mobSelectableTime"
:startPlaceholder="startPlaceholder" :endPlaceholder="endPlaceholder" :startPlaceholder="startPlaceholder" :endPlaceholder="endPlaceholder"
:pleStatus="endMultipleStatus" :showMonth="false" :range="isRange" :typeHasTime="hasTime" :insert="false" :default-value="defaultValue"
:hideSecond="hideSecond" @confirm="mobileChange" @maskClose="close" /> :pleStatus="endMultipleStatus" :showMonth="false" :range="isRange" :hasTime="hasTime" :insert="false"
:hideSecond="hideSecond" @confirm="mobileChange" @maskClose="close" @close="close"/>
</view> </view>
</template> </template>
<script> <script>
@ -125,16 +124,18 @@
* @property {Boolean} border = [true|false] 是否有边框 * @property {Boolean} border = [true|false] 是否有边框
* @property {Boolean} disabled = [true|false] 是否禁用 * @property {Boolean} disabled = [true|false] 是否禁用
* @property {Boolean} clearIcon = [true|false] 是否显示清除按钮(仅PC端适用) * @property {Boolean} clearIcon = [true|false] 是否显示清除按钮(仅PC端适用)
* @property {[String} defaultValue 选择器打开时默认显示的时间
* @event {Function} change 确定日期时触发的事件 * @event {Function} change 确定日期时触发的事件
* @event {Function} maskClick 点击遮罩层触发的事件 * @event {Function} maskClick 点击遮罩层触发的事件
* @event {Function} show 打开弹出层 * @event {Function} show 打开弹出层
* @event {Function} close 关闭弹出层 * @event {Function} close 关闭弹出层
* @event {Function} clear 清除上次选中的状态和值 * @event {Function} clear 清除上次选中的状态和值
**/ **/
import calendar from './calendar.vue' import Calendar from './calendar.vue'
import timePicker from './time-picker.vue' import TimePicker from './time-picker.vue'
import { initVueI18n } from '@dcloudio/uni-i18n' import { initVueI18n } from '@dcloudio/uni-i18n'
import i18nMessages from './i18n/index.js' import i18nMessages from './i18n/index.js'
import { getDateTime, getDate, getTime, getDefaultSecond, dateCompare, checkDate, fixIosDateFormat } from './util'
export default { export default {
name: 'UniDatetimePicker', name: 'UniDatetimePicker',
@ -142,8 +143,8 @@
virtualHost: true virtualHost: true
}, },
components: { components: {
calendar, Calendar,
timePicker TimePicker
}, },
data() { data() {
return { return {
@ -153,14 +154,13 @@
inputDate: '', inputDate: '',
calendarDate: '', calendarDate: '',
pickerTime: '', pickerTime: '',
// 范围选 calendarRange: {
caleRange: {
startDate: '', startDate: '',
startTime: '', startTime: '',
endDate: '', endDate: '',
endTime: '' endTime: ''
}, },
range: { displayRangeValue: {
startDate: '', startDate: '',
endDate: '', endDate: '',
}, },
@ -184,7 +184,7 @@
fulldate: '' fulldate: ''
}, },
pickerVisible: false, pickerVisible: false,
popover: null, pickerPositionStyle: null,
isEmitValue: false, isEmitValue: false,
isPhone: false, isPhone: false,
isFirstShow: true, isFirstShow: true,
@ -221,7 +221,7 @@
default: '' default: ''
}, },
startPlaceholder: { startPlaceholder: {
type: String, type: String,
default: '' default: ''
}, },
endPlaceholder: { endPlaceholder: {
@ -247,6 +247,10 @@
hideSecond: { hideSecond: {
type: [Boolean], type: [Boolean],
default: false default: false
},
defaultValue: {
type: [String, Object, Array],
default: ''
} }
}, },
watch: { watch: {
@ -285,13 +289,9 @@
immediate: true, immediate: true,
handler(newVal) { handler(newVal) {
if (!newVal) return if (!newVal) return
const { this.calendarRange.startDate = getDate(newVal)
defDate,
defTime
} = this.parseDate(newVal)
this.caleRange.startDate = defDate
if (this.hasTime) { if (this.hasTime) {
this.caleRange.startTime = defTime this.calendarRange.startTime = getTime(newVal)
} }
} }
}, },
@ -299,39 +299,33 @@
immediate: true, immediate: true,
handler(newVal) { handler(newVal) {
if (!newVal) return if (!newVal) return
const { this.calendarRange.endDate = getDate(newVal)
defDate,
defTime
} = this.parseDate(newVal)
this.caleRange.endDate = defDate
if (this.hasTime) { if (this.hasTime) {
this.caleRange.endTime = defTime this.calendarRange.endTime = getTime(newVal, this.hideSecond)
} }
} }
}, },
}, },
computed: { computed: {
reactStartTime() { timepickerStartTime() {
const activeDate = this.isRange ? this.tempRange.startDate : this.inputDate const activeDate = this.isRange ? this.tempRange.startDate : this.inputDate
const res = activeDate === this.caleRange.startDate ? this.caleRange.startTime : '' return activeDate === this.calendarRange.startDate ? this.calendarRange.startTime : ''
return res
}, },
reactEndTime() { timepickerEndTime() {
const activeDate = this.isRange ? this.tempRange.endDate : this.inputDate const activeDate = this.isRange ? this.tempRange.endDate : this.inputDate
const res = activeDate === this.caleRange.endDate ? this.caleRange.endTime : '' return activeDate === this.calendarRange.endDate ? this.calendarRange.endTime : ''
return res
}, },
reactMobDefTime() { mobileCalendarTime() {
const times = { const timeRange = {
start: this.tempRange.startTime, start: this.tempRange.startTime,
end: this.tempRange.endTime end: this.tempRange.endTime
} }
return this.isRange ? times : this.pickerTime return this.isRange ? timeRange : this.pickerTime
}, },
mobSelectableTime() { mobSelectableTime() {
return { return {
start: this.caleRange.startTime, start: this.calendarRange.startTime,
end: this.caleRange.endTime end: this.calendarRange.endTime
} }
}, },
datePopupWidth() { datePopupWidth() {
@ -379,7 +373,7 @@
return this.i18nT("uni-datetime-picker.clear") return this.i18nT("uni-datetime-picker.clear")
}, },
showClearIcon() { showClearIcon() {
return this.clearIcon && !this.disabled && (this.displayValue || (this.range.startDate && this.range.endDate)) return this.clearIcon && !this.disabled && (this.displayValue || (this.displayRangeValue.startDate && this.displayRangeValue.endDate))
} }
}, },
created() { created() {
@ -392,7 +386,7 @@
this.i18nT = vueI18n.t this.i18nT = vueI18n.t
}, },
initPicker(newVal) { initPicker(newVal) {
if (!newVal || Array.isArray(newVal) && !newVal.length) { if ((!newVal && !this.defaultValue) || Array.isArray(newVal) && !newVal.length) {
this.$nextTick(() => { this.$nextTick(() => {
this.clear(false) this.clear(false)
}) })
@ -400,36 +394,40 @@
} }
if (!Array.isArray(newVal) && !this.isRange) { if (!Array.isArray(newVal) && !this.isRange) {
const { if(newVal){
defDate, this.displayValue = this.inputDate = this.calendarDate = getDate(newVal)
defTime if (this.hasTime) {
} = this.parseDate(newVal) this.pickerTime = getTime(newVal, this.hideSecond)
this.displayValue = defDate this.displayValue = `${this.displayValue} ${this.pickerTime}`
this.inputDate = defDate }
this.calendarDate = defDate }else if(this.defaultValue){
if (this.hasTime) { this.inputDate = this.calendarDate = getDate(this.defaultValue)
this.displayValue = defDate + ' ' + defTime if(this.hasTime){
this.pickerTime = defTime this.pickerTime = getTime(this.defaultValue, this.hideSecond)
} }
}
} else { } else {
const [before, after] = newVal const [before, after] = newVal
if (!before && !after) return if (!before && !after) return
const defBefore = this.parseDate(before) const beforeDate = getDate(before)
const defAfter = this.parseDate(after) const beforeTime = getTime(before, this.hideSecond)
const startDate = defBefore.defDate
const endDate = defAfter.defDate const afterDate = getDate(after)
this.range.startDate = this.tempRange.startDate = startDate const afterTime = getTime(after, this.hideSecond)
this.range.endDate = this.tempRange.endDate = endDate const startDate = beforeDate
const endDate = afterDate
this.displayRangeValue.startDate = this.tempRange.startDate = startDate
this.displayRangeValue.endDate = this.tempRange.endDate = endDate
if (this.hasTime) { if (this.hasTime) {
this.range.startDate = defBefore.defDate + ' ' + defBefore.defTime this.displayRangeValue.startDate = `${beforeDate} ${beforeTime}`
this.range.endDate = defAfter.defDate + ' ' + defAfter.defTime this.displayRangeValue.endDate = `${afterDate} ${afterTime}`
this.tempRange.startTime = defBefore.defTime this.tempRange.startTime = beforeTime
this.tempRange.endTime = defAfter.defTime this.tempRange.endTime = afterTime
} }
const defaultRange = { const defaultRange = {
before: defBefore.defDate, before: beforeDate,
after: defAfter.defDate after: afterDate
} }
this.startMultipleStatus = Object.assign({}, this.startMultipleStatus, defaultRange, { this.startMultipleStatus = Object.assign({}, this.startMultipleStatus, defaultRange, {
which: 'right' which: 'right'
@ -452,6 +450,10 @@
right.setDate(this.$refs.right.nowDate.fullDate) right.setDate(this.$refs.right.nowDate.fullDate)
}, },
platform() { platform() {
if(typeof navigator !== "undefined"){
this.isPhone = navigator.userAgent.toLowerCase().indexOf('mobile') !== -1
return
}
const { windowWidth } = uni.getSystemInfoSync() const { windowWidth } = uni.getSystemInfoSync()
this.isPhone = windowWidth <= 500 this.isPhone = windowWidth <= 500
this.windowWidth = windowWidth this.windowWidth = windowWidth
@ -462,16 +464,18 @@
} }
this.platform() this.platform()
if (this.isPhone) { if (this.isPhone) {
this.$refs.mobile.open() setTimeout(() => {
this.$refs.mobile.open()
}, 0);
return return
} }
this.popover = { this.pickerPositionStyle = {
top: '10px' top: '10px'
} }
const dateEditor = uni.createSelectorQuery().in(this).select(".uni-date-editor") const dateEditor = uni.createSelectorQuery().in(this).select(".uni-date-editor")
dateEditor.boundingClientRect(rect => { dateEditor.boundingClientRect(rect => {
if (this.windowWidth - rect.left < this.datePopupWidth) { if (this.windowWidth - rect.left < this.datePopupWidth) {
this.popover.right = 0 this.pickerPositionStyle.right = 0
} }
}).exec() }).exec()
setTimeout(() => { setTimeout(() => {
@ -481,14 +485,16 @@
const { const {
startDate, startDate,
endDate endDate
} = this.range } = this.calendarRange
if (startDate && endDate) { if (startDate && endDate) {
if (this.diffDate(startDate, endDate) < 30) { if (this.diffDate(startDate, endDate) < 30) {
this.$refs.right.next() this.$refs.right.changeMonth('pre')
} }
} else { } else {
this.$refs.right.next() this.$refs.right.changeMonth('next')
this.$refs.right.cale.lastHover = false if(this.isPhone){
this.$refs.right.cale.lastHover = false;
}
} }
} }
@ -525,13 +531,13 @@
} }
} }
this.$emit('change', value)
this.$emit('input', value)
this.$emit('update:modelValue', value) this.$emit('update:modelValue', value)
this.$emit('input', value)
this.$emit('change', value)
this.isEmitValue = true this.isEmitValue = true
}, },
createTimestamp(date) { createTimestamp(date) {
date = this.fixIosDateFormat(date) date = fixIosDateFormat(date)
return Date.parse(new Date(date)) return Date.parse(new Date(date))
}, },
singleChange(e) { singleChange(e) {
@ -540,12 +546,10 @@
this.confirmSingleChange() this.confirmSingleChange()
}, },
confirmSingleChange() { confirmSingleChange() {
if (!this.inputDate) { if(!checkDate(this.inputDate)){
this.pickerVisible = false const now = new Date()
return this.calendarDate = this.inputDate = getDate(now)
} this.pickerTime = getTime(now, this.hideSecond)
if(!this.checkDate(this.inputDate)){
this.inputDate = this.getDate(Date.now())
} }
let startLaterInputDate = false let startLaterInputDate = false
@ -553,10 +557,10 @@
if(this.start) { if(this.start) {
let startString = this.start let startString = this.start
if(typeof this.start === 'number'){ if(typeof this.start === 'number'){
startString = this.getDateTime(this.start) startString = getDateTime(this.start, this.hideSecond)
} }
[startDate, startTime] = startString.split(' ') [startDate, startTime] = startString.split(' ')
if(this.start && !this.dateCompare(startDate, this.inputDate)) { if(this.start && !dateCompare(startDate, this.inputDate)) {
startLaterInputDate = true startLaterInputDate = true
this.inputDate = startDate this.inputDate = startDate
} }
@ -567,23 +571,23 @@
if(this.end) { if(this.end) {
let endString = this.end let endString = this.end
if(typeof this.end === 'number'){ if(typeof this.end === 'number'){
endString = this.getDateTime(this.end) endString = getDateTime(this.end, this.hideSecond)
} }
[endDate, endTime] = endString.split(' ') [endDate, endTime] = endString.split(' ')
if(this.end && !this.dateCompare(this.inputDate, endDate)) { if(this.end && !dateCompare(this.inputDate, endDate)) {
endEarlierInputDate = true endEarlierInputDate = true
this.inputDate = endDate this.inputDate = endDate
} }
} }
if (this.hasTime) { if (this.hasTime) {
if(startLaterInputDate){ if(startLaterInputDate){
this.pickerTime = startTime || this.getDefaultSecond() this.pickerTime = startTime || getDefaultSecond(this.hideSecond)
} }
if(endEarlierInputDate){ if(endEarlierInputDate){
this.pickerTime = endTime || this.getDefaultSecond() this.pickerTime = endTime || getDefaultSecond(this.hideSecond)
} }
if(!this.pickerTime){ if(!this.pickerTime){
this.pickerTime = this.getTime(Date.now()) this.pickerTime = getTime(Date.now(), this.hideSecond)
} }
this.displayValue = `${this.inputDate} ${this.pickerTime}` this.displayValue = `${this.inputDate} ${this.pickerTime}`
} else { } else {
@ -621,12 +625,14 @@
this.endMultipleStatus = Object.assign({}, this.endMultipleStatus, obj) this.endMultipleStatus = Object.assign({}, this.endMultipleStatus, obj)
}, },
mobileChange(e) { mobileChange(e) {
this.close()
if (this.isRange) { if (this.isRange) {
const {before, after} = e.range const {before, after} = e.range
if(!before || !after){ if(!before || !after){
return return
} }
this.handleStartAndEnd(before, after, true) this.handleStartAndEnd(before, after, true)
if (this.hasTime) { if (this.hasTime) {
@ -646,7 +652,6 @@
} }
this.setEmit(this.displayValue) this.setEmit(this.displayValue)
} }
this.$refs.mobile.close()
}, },
rangeChange(before, after) { rangeChange(before, after) {
if (!(before && after)) return if (!(before && after)) return
@ -659,11 +664,11 @@
this.pickerVisible = false this.pickerVisible = false
return return
} }
if(!this.checkDate(this.tempRange.startDate)){ if(!checkDate(this.tempRange.startDate)){
this.tempRange.startDate = this.getDate(Date.now()) this.tempRange.startDate = getDate(Date.now())
} }
if(!this.checkDate(this.tempRange.endDate)){ if(!checkDate(this.tempRange.endDate)){
this.tempRange.endDate = this.getDate(Date.now()) this.tempRange.endDate = getDate(Date.now())
} }
let start, end let start, end
@ -674,14 +679,14 @@
if(this.start) { if(this.start) {
let startString = this.start let startString = this.start
if(typeof this.start === 'number'){ if(typeof this.start === 'number'){
startString = this.getDateTime(this.start) startString = getDateTime(this.start, this.hideSecond)
} }
[startDate,startTime] = startString.split(' ') [startDate,startTime] = startString.split(' ')
if(this.start && !this.dateCompare(this.start, this.tempRange.startDate)) { if(this.start && !dateCompare(this.start, this.tempRange.startDate)) {
startDateLaterRangeStartDate = true startDateLaterRangeStartDate = true
this.tempRange.startDate = startDate this.tempRange.startDate = startDate
} }
if(this.start && !this.dateCompare(this.start, this.tempRange.endDate)) { if(this.start && !dateCompare(this.start, this.tempRange.endDate)) {
startDateLaterRangeEndDate = true startDateLaterRangeEndDate = true
this.tempRange.endDate = startDate this.tempRange.endDate = startDate
} }
@ -692,48 +697,48 @@
if(this.end) { if(this.end) {
let endString = this.end let endString = this.end
if(typeof this.end === 'number'){ if(typeof this.end === 'number'){
endString = this.getDateTime(this.end) endString = getDateTime(this.end, this.hideSecond)
} }
[endDate,endTime] = endString.split(' ') [endDate,endTime] = endString.split(' ')
if(this.end && !this.dateCompare(this.tempRange.startDate, this.end)) { if(this.end && !dateCompare(this.tempRange.startDate, this.end)) {
endDateEarlierRangeStartDate = true endDateEarlierRangeStartDate = true
this.tempRange.startDate = endDate this.tempRange.startDate = endDate
} }
if(this.end && !this.dateCompare(this.tempRange.endDate, this.end)) { if(this.end && !dateCompare(this.tempRange.endDate, this.end)) {
endDateEarlierRangeEndDate = true endDateEarlierRangeEndDate = true
this.tempRange.endDate = endDate this.tempRange.endDate = endDate
} }
} }
if (!this.hasTime) { if (!this.hasTime) {
start = this.range.startDate = this.tempRange.startDate start = this.displayRangeValue.startDate = this.tempRange.startDate
end = this.range.endDate = this.tempRange.endDate end = this.displayRangeValue.endDate = this.tempRange.endDate
} else { } else {
if(startDateLaterRangeStartDate){ if(startDateLaterRangeStartDate){
this.tempRange.startTime = startTime || this.getDefaultSecond() this.tempRange.startTime = startTime || getDefaultSecond(this.hideSecond)
}else if(endDateEarlierRangeStartDate){ }else if(endDateEarlierRangeStartDate){
this.tempRange.startTime = endTime || this.getDefaultSecond() this.tempRange.startTime = endTime || getDefaultSecond(this.hideSecond)
} }
if(!this.tempRange.startTime){ if(!this.tempRange.startTime){
this.tempRange.startTime = this.getTime(Date.now()) this.tempRange.startTime = getTime(Date.now(), this.hideSecond)
} }
if(startDateLaterRangeEndDate){ if(startDateLaterRangeEndDate){
this.tempRange.endTime = startTime || this.getDefaultSecond() this.tempRange.endTime = startTime || getDefaultSecond(this.hideSecond)
}else if(endDateEarlierRangeEndDate){ }else if(endDateEarlierRangeEndDate){
this.tempRange.endTime = endTime || this.getDefaultSecond() this.tempRange.endTime = endTime || getDefaultSecond(this.hideSecond)
} }
if(!this.tempRange.endTime){ if(!this.tempRange.endTime){
this.tempRange.endTime = this.getTime(Date.now()) this.tempRange.endTime = getTime(Date.now(), this.hideSecond)
} }
start = this.range.startDate = `${this.tempRange.startDate} ${this.tempRange.startTime}` start = this.displayRangeValue.startDate = `${this.tempRange.startDate} ${this.tempRange.startTime}`
end = this.range.endDate = `${this.tempRange.endDate} ${this.tempRange.endTime}` end = this.displayRangeValue.endDate = `${this.tempRange.endDate} ${this.tempRange.endTime}`
} }
if(!this.dateCompare(start,end)){ if(!dateCompare(start,end)){
[start, end] = [end, start] [start, end] = [end, start]
} }
this.range.startDate = start this.displayRangeValue.startDate = start
this.range.endDate = end this.displayRangeValue.endDate = end
const displayRange = [start, end] const displayRange = [start, end]
this.setEmit(displayRange) this.setEmit(displayRange)
this.pickerVisible = false this.pickerVisible = false
@ -742,7 +747,7 @@
if (!(before && after)) return if (!(before && after)) return
const type = temp ? 'tempRange' : 'range' const type = temp ? 'tempRange' : 'range'
const isStartEarlierEnd = this.dateCompare(before, after) const isStartEarlierEnd = dateCompare(before, after)
this[type].startDate = isStartEarlierEnd ? before : after this[type].startDate = isStartEarlierEnd ? before : after
this[type].endDate = isStartEarlierEnd ? after : before this[type].endDate = isStartEarlierEnd ? after : before
}, },
@ -785,8 +790,8 @@
this.$emit('update:modelValue', '') this.$emit('update:modelValue', '')
} }
} else { } else {
this.range.startDate = '' this.displayRangeValue.startDate = ''
this.range.endDate = '' this.displayRangeValue.endDate = ''
this.tempRange.startDate = '' this.tempRange.startDate = ''
this.tempRange.startTime = '' this.tempRange.startTime = ''
this.tempRange.endDate = '' this.tempRange.endDate = ''
@ -796,7 +801,7 @@
} else { } else {
this.$refs.left && this.$refs.left.clearCalender() this.$refs.left && this.$refs.left.clearCalender()
this.$refs.right && this.$refs.right.clearCalender() this.$refs.right && this.$refs.right.clearCalender()
this.$refs.right && this.$refs.right.next() this.$refs.right && this.$refs.right.changeMonth('next')
} }
if (needEmit) { if (needEmit) {
this.$emit('change', []) this.$emit('change', [])
@ -804,66 +809,7 @@
this.$emit('update:modelValue', []) this.$emit('update:modelValue', [])
} }
} }
}, }
parseDate(date) {
date = this.fixIosDateFormat(date)
const defVal = new Date(date)
const year = defVal.getFullYear()
const month = defVal.getMonth() + 1
const day = defVal.getDate()
const hour = defVal.getHours()
const minute = defVal.getMinutes()
const second = defVal.getSeconds()
const defDate = year + '-' + this.lessTen(month) + '-' + this.lessTen(day)
const defTime = this.lessTen(hour) + ':' + this.lessTen(minute) + (this.hideSecond ? '' : (':' + this
.lessTen(second)))
return {
defDate,
defTime
}
},
lessTen(item) {
return item < 10 ? '0' + item : item
},
//兼容 iOS、safari 日期格式
fixIosDateFormat(value) {
// #ifndef MP
if (typeof value === 'string') {
value = value.replace(/-/g, '/')
}
// #endif
return value
},
checkDate(date){
const dateReg = /((19|20)\d{2})(-|\/)\d{1,2}(-|\/)\d{1,2}/g
return date.match(dateReg)
},
getDateTime(date){
return `${this.getDate(date)} ${this.getTime(date)}`
},
getDate(date){
date = new Date(date)
const year = date.getFullYear()
const month = date.getMonth()+1
const day = date.getDate()
return `${year}-${this.addZero(month)}-${this.addZero(day)}`
},
getTime(date){
date = new Date(date)
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return this.hideSecond ? `${this.addZero(hour)}:${this.addZero(minute)}` : `${this.addZero(hour)}:${this.addZero(minute)}:${this.addZero(second)}`
},
addZero(num) {
if(num < 10){
num = `0${num}`
}
return num
},
getDefaultSecond() {
return this.hideSecond ? '00:00' : '00:00:00'
}
} }
} }
</script> </script>
@ -890,7 +836,11 @@
padding-left: 3px; padding-left: 3px;
} }
.range-separator{ .range-separator{
height: 35px;
/* #ifndef MP */
padding: 0 2px; padding: 0 2px;
/* #endif */
line-height: 35px;
} }
} }
@ -917,15 +867,18 @@
.uni-date__x-input { .uni-date__x-input {
width: auto; width: auto;
position: relative;
overflow: hidden;
flex: 1;
line-height: 1;
font-size: 14px;
height: 35px; height: 35px;
/* #ifndef MP */
padding-left: 5px;
/* #endif */
position: relative;
flex: 1;
line-height: 35px;
font-size: 14px;
overflow: hidden;
} }
.t-c { .text-center {
text-align: center; text-align: center;
} }
@ -1023,7 +976,7 @@
opacity: 0.8; opacity: 0.8;
} }
.popup-x-footer .confirm { .popup-x-footer .confirm-text {
margin-left: 20px; margin-left: 20px;
color: $uni-primary; color: $uni-primary;
} }

View File

@ -1,27 +1,24 @@
class Calendar { class Calendar {
constructor({ constructor({
date,
selected, selected,
startDate, startDate,
endDate, endDate,
range, range,
// multipleStatus
} = {}) { } = {}) {
// 当前日期 // 当前日期
this.date = this.getDate(new Date()) // 当前初入日期 this.date = this.getDateObj(new Date()) // 当前初入日期
// 打点信息 // 打点信息
this.selected = selected || []; this.selected = selected || [];
// 范围开始 // 起始时间
this.startDate = startDate this.startDate = startDate
// 范围结束 // 终止时间
this.endDate = endDate this.endDate = endDate
// 是否范围选择
this.range = range this.range = range
// 多选状态 // 多选状态
this.cleanMultipleStatus() this.cleanMultipleStatus()
// 每周日期 // 每周日期
this.weeks = {} this.weeks = {}
// this._getWeek(this.date.fullDate)
// this.multipleStatus = multipleStatus
this.lastHover = false this.lastHover = false
} }
/** /**
@ -29,8 +26,8 @@ class Calendar {
* @param {Object} date * @param {Object} date
*/ */
setDate(date) { setDate(date) {
this.selectDate = this.getDate(date) const selectDate = this.getDateObj(date)
this._getWeek(this.selectDate.fullDate) this.getWeeks(selectDate.fullDate)
} }
/** /**
@ -44,103 +41,82 @@ class Calendar {
} }
} }
/** setStartDate(startDate) {
* 重置开始日期
*/
resetSatrtDate(startDate) {
// 范围开始
this.startDate = startDate this.startDate = startDate
} }
/** setEndDate(endDate) {
* 重置结束日期
*/
resetEndDate(endDate) {
// 范围结束
this.endDate = endDate this.endDate = endDate
} }
getPreMonthObj(date){
date = fixIosDateFormat(date)
date = new Date(date)
const oldMonth = date.getMonth()
date.setMonth(oldMonth - 1)
const newMonth = date.getMonth()
if(oldMonth !== 0 && newMonth - oldMonth === 0){
date.setMonth(newMonth - 1)
}
return this.getDateObj(date)
}
getNextMonthObj(date){
date = fixIosDateFormat(date)
date = new Date(date)
const oldMonth = date.getMonth()
date.setMonth(oldMonth + 1)
const newMonth = date.getMonth()
if(newMonth - oldMonth > 1){
date.setMonth(newMonth - 1)
}
return this.getDateObj(date)
}
/** /**
* 获取任意时间 * 获取指定格式Date对象
*/ */
getDate(date, AddDayCount = 0, str = 'day') { getDateObj(date) {
if (!date) { date = fixIosDateFormat(date)
date = new Date() date = new Date(date)
}
if (typeof date !== 'object') {
date = date.replace(/-/g, '/')
}
const dd = new Date(date)
switch (str) {
case 'day':
dd.setDate(dd.getDate() + AddDayCount) // 获取AddDayCount天后的日期
break
case 'month':
if (dd.getDate() === 31 && AddDayCount>0) {
dd.setDate(dd.getDate() + AddDayCount)
} else {
const preMonth = dd.getMonth()
dd.setMonth(preMonth + AddDayCount) // 获取AddDayCount天后的日期
const nextMonth = dd.getMonth()
// 处理 pre 切换月份目标月份为2月没有当前日(30 31) 切换错误问题
if(AddDayCount<0 && preMonth!==0 && nextMonth-preMonth>AddDayCount){
dd.setMonth(nextMonth+(nextMonth-preMonth+AddDayCount))
}
// 处理 next 切换月份目标月份为2月没有当前日(30 31) 切换错误问题
if(AddDayCount>0 && nextMonth-preMonth>AddDayCount){
dd.setMonth(nextMonth-(nextMonth-preMonth-AddDayCount))
}
}
break
case 'year':
dd.setFullYear(dd.getFullYear() + AddDayCount) // 获取AddDayCount天后的日期
break
}
const y = dd.getFullYear()
const m = dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1 // 获取当前月份的日期,不足10补0
const d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate() // 获取当前几号,不足10补0
return { return {
fullDate: y + '-' + m + '-' + d, fullDate: getDate(date),
year: y, year: date.getFullYear(),
month: m, month: addZero(date.getMonth() + 1),
date: d, date: addZero(date.getDate()),
day: dd.getDay() day: date.getDay()
} }
} }
/** /**
* 获取上月剩余天数 * 获取上一个月日期集合
*/ */
_getLastMonthDays(firstDay, full) { getPreMonthDays(amount, dateObj) {
let dateArr = [] const result = []
for (let i = firstDay; i > 0; i--) { for (let i = amount - 1; i >= 0; i--) {
const beforeDate = new Date(full.year, full.month - 1, -i + 1).getDate() const month = dateObj.month - 1
dateArr.push({ result.push({
date: beforeDate, date: new Date(dateObj.year, month, -i).getDate(),
month: full.month - 1, month,
disable: true disable: true
}) })
} }
return dateArr return result
} }
/** /**
* 获取本月天数 * 获取本月日期集合
*/ */
_currentMonthDys(dateData, full) { getCurrentMonthDays(amount, dateObj) {
let dateArr = [] const result = []
let fullDate = this.date.fullDate const fullDate = this.date.fullDate
for (let i = 1; i <= dateData; i++) { for (let i = 1; i <= amount; i++) {
let isinfo = false const currentDate = `${dateObj.year}-${dateObj.month}-${addZero(i)}`
let nowDate = full.year + '-' + (full.month < 10 ? const isToday = fullDate === currentDate
full.month : full.month) + '-' + (i < 10 ?
'0' + i : i)
// 是否今天
let isDay = fullDate === nowDate
// 获取打点信息 // 获取打点信息
let info = this.selected && this.selected.find((item) => { const info = this.selected && this.selected.find((item) => {
if (this.dateEqual(nowDate, item.date)) { if (this.dateEqual(currentDate, item.date)) {
return item return item
} }
}) })
@ -149,62 +125,52 @@ class Calendar {
let disableBefore = true let disableBefore = true
let disableAfter = true let disableAfter = true
if (this.startDate) { if (this.startDate) {
// let dateCompBefore = this.dateCompare(this.startDate, fullDate) disableBefore = dateCompare(this.startDate, currentDate)
// disableBefore = this.dateCompare(dateCompBefore ? this.startDate : fullDate, nowDate)
disableBefore = this.dateCompare(this.startDate, nowDate)
} }
if (this.endDate) { if (this.endDate) {
// let dateCompAfter = this.dateCompare(fullDate, this.endDate) disableAfter = dateCompare(currentDate, this.endDate)
// disableAfter = this.dateCompare(nowDate, dateCompAfter ? this.endDate : fullDate)
disableAfter = this.dateCompare(nowDate, this.endDate)
}
let multiples = this.multipleStatus.data
let checked = false
let multiplesStatus = -1
if (this.range) {
if (multiples) {
multiplesStatus = multiples.findIndex((item) => {
return this.dateEqual(item, nowDate)
})
}
if (multiplesStatus !== -1) {
checked = true
}
}
let data = {
fullDate: nowDate,
year: full.year,
date: i,
multiple: this.range ? checked : false,
beforeMultiple: this.isLogicBefore(nowDate, this.multipleStatus.before, this.multipleStatus.after),
afterMultiple: this.isLogicAfter(nowDate, this.multipleStatus.before, this.multipleStatus.after),
month: full.month,
disable: !(disableBefore && disableAfter),
isDay,
userChecked: false
}
if (info) {
data.extraInfo = info
} }
dateArr.push(data) let multiples = this.multipleStatus.data
let multiplesStatus = -1
if (this.range && multiples) {
multiplesStatus = multiples.findIndex((item) => {
return this.dateEqual(item, currentDate)
})
}
const checked = multiplesStatus !== -1
result.push({
fullDate: currentDate,
year: dateObj.year,
date: i,
multiple: this.range ? checked : false,
beforeMultiple: this.isLogicBefore(currentDate, this.multipleStatus.before, this.multipleStatus.after),
afterMultiple: this.isLogicAfter(currentDate, this.multipleStatus.before, this.multipleStatus.after),
month: dateObj.month,
disable: (this.startDate && !dateCompare(this.startDate, currentDate)) || (this.endDate && !dateCompare(currentDate,this.endDate)),
isToday,
userChecked: false,
extraInfo: info
})
} }
return dateArr return result
} }
/** /**
* 获取下月天数 * 获取下一个月日期集合
*/ */
_getNextMonthDays(surplus, full) { _getNextMonthDays(amount, dateObj) {
let dateArr = [] const result = []
for (let i = 1; i < surplus + 1; i++) { const month = dateObj.month + 1
dateArr.push({ for (let i = 1; i <= amount; i++) {
result.push({
date: i, date: i,
month: Number(full.month) + 1, month,
disable: true disable: true
}) })
} }
return dateArr return result
} }
/** /**
@ -215,58 +181,37 @@ class Calendar {
if (!date) { if (!date) {
date = new Date() date = new Date()
} }
const dateInfo = this.canlender.find(item => item.fullDate === this.getDate(date).fullDate)
return dateInfo
}
/** return this.calendar.find(item => item.fullDate === this.getDateObj(date).fullDate)
* 比较时间大小
*/
dateCompare(startDate, endDate) {
// 计算截止时间
startDate = new Date(startDate.replace('-', '/').replace('-', '/'))
// 计算详细项的截止时间
endDate = new Date(endDate.replace('-', '/').replace('-', '/'))
if (startDate <= endDate) {
return true
} else {
return false
}
} }
/** /**
* 比较时间是否相等 * 比较时间是否相等
*/ */
dateEqual(before, after) { dateEqual(before, after) {
// 计算截止时间 before = new Date(fixIosDateFormat(before))
before = new Date(before.replace('-', '/').replace('-', '/')) after = new Date(fixIosDateFormat(after))
// 计算详细项的截止时间 return before.valueOf() === after.valueOf()
after = new Date(after.replace('-', '/').replace('-', '/'))
if (before.getTime() - after.getTime() === 0) {
return true
} else {
return false
}
} }
/** /**
* 比较真实起始日期 * 比较真实起始日期
*/ */
isLogicBefore(currentDay, before, after) { isLogicBefore(currentDate, before, after) {
let logicBefore = before let logicBefore = before
if (before && after) { if (before && after) {
logicBefore = this.dateCompare(before, after) ? before : after logicBefore = dateCompare(before, after) ? before : after
} }
return this.dateEqual(logicBefore, currentDay) return this.dateEqual(logicBefore, currentDate)
} }
isLogicAfter(currentDay, before, after) { isLogicAfter(currentDate, before, after) {
let logicAfter = after let logicAfter = after
if (before && after) { if (before && after) {
logicAfter = this.dateCompare(before, after) ? after : before logicAfter = dateCompare(before, after) ? after : before
} }
return this.dateEqual(logicAfter, currentDay) return this.dateEqual(logicAfter, currentDate)
} }
/** /**
@ -286,7 +231,7 @@ class Calendar {
var unixDe = de.getTime() - 24 * 60 * 60 * 1000 var unixDe = de.getTime() - 24 * 60 * 60 * 1000
for (var k = unixDb; k <= unixDe;) { for (var k = unixDb; k <= unixDe;) {
k = k + 24 * 60 * 60 * 1000 k = k + 24 * 60 * 60 * 1000
arr.push(this.getDate(new Date(parseInt(k))).fullDate) arr.push(this.getDateObj(new Date(parseInt(k))).fullDate)
} }
return arr return arr
} }
@ -295,11 +240,12 @@ class Calendar {
* 获取多选状态 * 获取多选状态
*/ */
setMultiple(fullDate) { setMultiple(fullDate) {
if (!this.range) return
let { let {
before, before,
after after
} = this.multipleStatus } = this.multipleStatus
if (!this.range) return
if (before && after) { if (before && after) {
if (!this.lastHover) { if (!this.lastHover) {
this.lastHover = true this.lastHover = true
@ -316,7 +262,7 @@ class Calendar {
this.lastHover = false this.lastHover = false
} else { } else {
this.multipleStatus.after = fullDate this.multipleStatus.after = fullDate
if (this.dateCompare(this.multipleStatus.before, this.multipleStatus.after)) { if (dateCompare(this.multipleStatus.before, this.multipleStatus.after)) {
this.multipleStatus.data = this.geDateAll(this.multipleStatus.before, this.multipleStatus this.multipleStatus.data = this.geDateAll(this.multipleStatus.before, this.multipleStatus
.after); .after);
} else { } else {
@ -326,32 +272,28 @@ class Calendar {
this.lastHover = true this.lastHover = true
} }
} }
this._getWeek(fullDate) this.getWeeks(fullDate)
} }
/** /**
* 鼠标 hover 更新多选状态 * 鼠标 hover 更新多选状态
*/ */
setHoverMultiple(fullDate) { setHoverMultiple(fullDate) {
let { if (!this.range || this.lastHover) return
before,
after
} = this.multipleStatus
if (!this.range) return const { before } = this.multipleStatus
if (this.lastHover) return
if (!before) { if (!before) {
this.multipleStatus.before = fullDate this.multipleStatus.before = fullDate
} else { } else {
this.multipleStatus.after = fullDate this.multipleStatus.after = fullDate
if (this.dateCompare(this.multipleStatus.before, this.multipleStatus.after)) { if (dateCompare(this.multipleStatus.before, this.multipleStatus.after)) {
this.multipleStatus.data = this.geDateAll(this.multipleStatus.before, this.multipleStatus.after); this.multipleStatus.data = this.geDateAll(this.multipleStatus.before, this.multipleStatus.after);
} else { } else {
this.multipleStatus.data = this.geDateAll(this.multipleStatus.after, this.multipleStatus.before); this.multipleStatus.data = this.geDateAll(this.multipleStatus.after, this.multipleStatus.before);
} }
} }
this._getWeek(fullDate) this.getWeeks(fullDate)
} }
/** /**
@ -361,12 +303,12 @@ class Calendar {
this.multipleStatus.before = before this.multipleStatus.before = before
this.multipleStatus.after = after this.multipleStatus.after = after
if (before && after) { if (before && after) {
if (this.dateCompare(before, after)) { if (dateCompare(before, after)) {
this.multipleStatus.data = this.geDateAll(before, after); this.multipleStatus.data = this.geDateAll(before, after);
this._getWeek(after) this.getWeeks(after)
} else { } else {
this.multipleStatus.data = this.geDateAll(after, before); this.multipleStatus.data = this.geDateAll(after, before);
this._getWeek(before) this.getWeeks(before)
} }
} }
} }
@ -375,46 +317,87 @@ class Calendar {
* 获取每周数据 * 获取每周数据
* @param {Object} dateData * @param {Object} dateData
*/ */
_getWeek(dateData) { getWeeks(dateData) {
const { const {
fullDate,
year, year,
month, month,
date, } = this.getDateObj(dateData)
day
} = this.getDate(dateData) const preMonthDayAmount = new Date(year, month - 1, 1).getDay()
let firstDay = new Date(year, month - 1, 1).getDay() const preMonthDays = this.getPreMonthDays(preMonthDayAmount, this.getDateObj(dateData))
let currentDay = new Date(year, month, 0).getDate()
let dates = { const currentMonthDayAmount = new Date(year, month, 0).getDate()
lastMonthDays: this._getLastMonthDays(firstDay, this.getDate(dateData)), // 上个月末尾几天 const currentMonthDays = this.getCurrentMonthDays(currentMonthDayAmount, this.getDateObj(dateData))
currentMonthDys: this._currentMonthDys(currentDay, this.getDate(dateData)), // 本月天数
nextMonthDays: [], // 下个月开始几天 const nextMonthDayAmount = 42 - preMonthDayAmount - currentMonthDayAmount
weeks: [] const nextMonthDays = this._getNextMonthDays(nextMonthDayAmount, this.getDateObj(dateData))
const calendarDays = [...preMonthDays, ...currentMonthDays, ...nextMonthDays]
const weeks = new Array(6)
for (let i = 0; i < calendarDays.length; i++) {
const index = Math.floor(i / 7)
if(!weeks[index]){
weeks[index] = new Array(7)
}
weeks[index][i % 7] = calendarDays[i]
} }
let canlender = []
const surplus = 42 - (dates.lastMonthDays.length + dates.currentMonthDys.length) this.calendar = calendarDays
dates.nextMonthDays = this._getNextMonthDays(surplus, this.getDate(dateData))
canlender = canlender.concat(dates.lastMonthDays, dates.currentMonthDys, dates.nextMonthDays)
let weeks = {}
// 拼接数组 上个月开始几天 + 本月天数+ 下个月开始几天
for (let i = 0; i < canlender.length; i++) {
if (i % 7 === 0) {
weeks[parseInt(i / 7)] = new Array(7)
}
weeks[parseInt(i / 7)][i % 7] = canlender[i]
}
this.canlender = canlender
this.weeks = weeks this.weeks = weeks
} }
//静态方法
// static init(date) {
// if (!this.instance) {
// this.instance = new Calendar(date);
// }
// return this.instance;
// }
} }
function getDateTime(date, hideSecond){
return `${getDate(date)} ${getTime(date, hideSecond)}`
}
export default Calendar function getDate(date) {
date = fixIosDateFormat(date)
date = new Date(date)
const year = date.getFullYear()
const month = date.getMonth()+1
const day = date.getDate()
return `${year}-${addZero(month)}-${addZero(day)}`
}
function getTime(date, hideSecond){
date = fixIosDateFormat(date)
date = new Date(date)
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return hideSecond ? `${addZero(hour)}:${addZero(minute)}` : `${addZero(hour)}:${addZero(minute)}:${addZero(second)}`
}
function addZero(num) {
if(num < 10){
num = `0${num}`
}
return num
}
function getDefaultSecond(hideSecond) {
return hideSecond ? '00:00' : '00:00:00'
}
function dateCompare(startDate, endDate) {
startDate = new Date(fixIosDateFormat(startDate))
endDate = new Date(fixIosDateFormat(endDate))
return startDate <= endDate
}
function checkDate(date){
const dateReg = /((19|20)\d{2})(-|\/)\d{1,2}(-|\/)\d{1,2}/g
return date.match(dateReg)
}
const dateTimeReg = /^\d{4}-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])( [0-5]?[0-9]:[0-5]?[0-9]:[0-5]?[0-9])?$/
function fixIosDateFormat(value) {
if (typeof value === 'string' && dateTimeReg.test(value)) {
value = value.replace(/-/g, '/')
}
return value
}
export {Calendar, getDateTime, getDate, getTime, addZero, getDefaultSecond, dateCompare, checkDate, fixIosDateFormat}

View File

@ -1,7 +1,7 @@
{ {
"id": "uni-datetime-picker", "id": "uni-datetime-picker",
"displayName": "uni-datetime-picker 日期选择器", "displayName": "uni-datetime-picker 日期选择器",
"version": "2.2.19", "version": "2.2.25",
"description": "uni-datetime-picker 日期时间选择器,支持日历,支持范围选择", "description": "uni-datetime-picker 日期时间选择器,支持日历,支持范围选择",
"keywords": [ "keywords": [
"uni-datetime-picker", "uni-datetime-picker",