【问题标题】:Every year in september, my Date list skips a month and I cannot reproduce it每年九月,我的日期列表跳过一个月,我无法重现它
【发布时间】:2021-09-03 18:03:43
【问题描述】:

问题

我正在构建一个开源 Vue 应用程序。它有一个甘特图,可以将任务显示为时间线。它有一个供用户设置日期范围的选项,默认显示当前和下个月。

每年 9 月,这个图表都会打破。它不显示所有月份,而是跳过下个月:

这应该是它的样子:

关于此here 一直存在问题。

捕获

我无法重现此内容。即使我使用 Browserstack 能够使用我的用户正在使用的完全相同的浏览器/操作系统组合。到目前为止,它在我尝试过的所有设备和浏览器上都可以正常工作。因为我无法重现它,我无法真正调试它,更不用说修复它了。

这也暗示它只影响一些用户,而不是那么多。

代码

这是构建年/月/日数据结构的代码:

// Layout: years => [months => [days]]
let years = {}
for (
    let d = this.startDate;
    d <= this.endDate;
    d.setDate(d.getDate() + 1)
) {
    let date = new Date(d)
    if (years[date.getFullYear() + ''] === undefined) {
        years[date.getFullYear() + ''] = {}
    }
    if (
        years[date.getFullYear() + ''][date.getMonth() + ''] ===
        undefined
    ) {
        years[date.getFullYear() + ''][date.getMonth() + ''] = []
    }
    years[date.getFullYear() + ''][date.getMonth() + ''].push(date)
    this.fullWidth += this.dayWidth
}
this.$set(this, 'days', years) // I know, that variable name doesn't make any sense

然后我像这样向用户展示:

<template v-for="(y, yk) in days">
    <div :key="yk + 'year'" class="months">
        <div
            :key="mk + 'month'"
            class="month"
            v-for="(m, mk) in days[yk]"
        >
            {{
                new Date(
                    new Date(yk).setMonth(mk),
                ).toLocaleString('en-us', {month: 'long'})
            }},
            {{ new Date(yk).getFullYear() }}
            <div class="days">
                <div
                    :class="{ today: d.toDateString() === now.toDateString() }"
                    :key="dk + 'day'"
                    :style="{ width: dayWidth + 'px' }"
                    class="day"
                    v-for="(d, dk) in days[yk][mk]"
                >
                    <span class="theday" v-if="dayWidth > 25">
                        {{ d.getDate() }}
                    </span>
                    <span class="weekday" v-if="dayWidth > 25">
                        {{ d.toLocaleString('en-us', {weekday: 'short'}) }} 
                    </span>
                </div>
            </div>
        </div>
    </div>
</template>

组件的完整代码是here

【问题讨论】:

    标签: javascript vue.js date gantt-chart


    【解决方案1】:

    问题出在

    new Date(new Date(yk).setMonth(mk))
    

    例如,您希望 new Date(new Date(2021, 11, 31).setMonth(8)) 会在 2021 年 9 月结束?没有。将是 10 月 1 日,因为 9 月没有 31 天,只有 30 天。

    日期yk应该是每个月的第一天才能正确修改月份。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多