前言
在 GitHub 平台上逛组件库 Element Plus 时发现了一个 issue#11885 关于[i18n] [date-picker] 日期选择框格式化判断归属第几周不对。
Element Plus 日期选择器周数相关问题
问题 1:周数计算逻辑
Element Plus 日期选择器时间处理上选择的是第三方库 dayjs,关于周的计算分为 week 和 isoWeek 两种。
isoWeek 是指 ISO 标准下国际周数计算标准:1 月 4 日所在周为第一周。
week 则取决于 yearStart 的设置,不取决于周首日 weekStart 的设置,weekStart 控制的是弹出面板上的展示。
特别注意:不是所有的国际化配置文件都同时有 weekStart 和 yearStart 的设置,当 yearStart 未设置时默认取值为 1。
国际化设置时间相关时一定不用忘记导入 import 'dayjs/locale/zh-cn'
// dayjs
proto.week = function (week = null) {
if (week !== null) {
return this.add((week - this.week()) * 7, D)
}
const yearStart = this.$locale().yearStart || 1
if (this.month() === 11 && this.date() > 25) {
// d(this) is for badMutable
const nextYearStartDay = d(this).startOf(Y).add(1, Y).date(yearStart)
const thisEndOfWeek = d(this).endOf(W)
if (nextYearStartDay.isBefore(thisEndOfWeek)) {
return 1
}
}
const yearStartDay = d(this).startOf(Y).date(yearStart)
const yearStartWeek = yearStartDay.startOf(W).subtract(1, MS)
const diffInWeek = this.diff(yearStartWeek, W, true)
if (diffInWeek < 0) {
return d(this).startOf("week").week()
}
return Math.ceil(diffInWeek)
}
问题 2:周选择时格式化的问题
使用周选择器时使用 format 来格式化展示内容时需格外小心格式化问题。 dayjs 格式化相关参数链接地址 day.js.org/docs/en/plu… 。
| Format | Output | Description |
|---|---|---|
| Q | 1-4 | Quarter |
| Do | 1st | 2nd ... 31st Day of Month with ordinal |
| k | 1-24 | The hour, beginning at 1 |
| kk | 01-24 | The hour, 2-digits, beginning at 1 |
| X | 1360013296 | Unix Timestamp in second |
| x | 1360013296123 | Unix Timestamp in millisecond |
| w | 1 2 ... 52 | 53 Week of year ( dependent WeekOfYear plugin ) |
| ww | 01 02 ... 52 | 53 Week of year, 2-digits ( dependent WeekOfYear plugin ) |
| W | 1 2 ... 52 | 53 ISO Week of year ( dependent IsoWeek plugin ) |
| WW | 01 02 ... 52 | 53 ISO Week of year, 2-digits ( dependent IsoWeek plugin ) |
| wo | 1st 2nd ... 52nd | 53rd Week of year with ordinal ( dependent WeekOfYear plugin ) |
| gggg | 2017 | Week Year ( dependent WeekYear plugin ) |
| GGGG | 2017 | ISO Week Year ( dependent IsoWeek plugin ) |
| z | EST | Abbreviated named offset ( dependent Timezone plugin ) |
| zzz | Eastern | Standard Time Unabbreviated named offset ( dependent Timezone plugin ) |