我想使用Javascript / Vue将当前一周作为日期数组返回

问题描述

我正在尝试返回日期数组。与下面类似。我已经阅读了Moment和Luxon的文档,并在这里阅读了其他答案,但是似乎找不到适合我的用例的答案。

我希望有一个1周周期的数组,可以一次使用“下周”和“上周”按钮“分页”一次。

choicechips

解决方法

您可以简单地使用js Date获取当前日期,然后基于此日期,您可以使用get首个和最后一个日期。

请参考以下示例:

submit()

之后,您可以轻松获得该范围内的日期

,

在此示例中,使用计算属性非常重要,因为您可以更改星期(下一周或下一周)。

尝试类似的事情:

<template>
  <div>
    <div>
      <button @click="priorWeek">Prior Week</button>
      <span v-for="day in days" class="day">
        {{ day.toLocaleDateString() }}
      </span>
      <button @click="nextWeek">Next Week</button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'App',data: () => ({
    first: new Date(),}),computed: {
    days() {
      return [
        this.first,this.addDays(this.first,1),2),3),4),5),6),];
    },},methods: {
    addDays(date,days) {
      let newDate = new Date(date);
      newDate.setDate(this.first.getDate() + days);
      return newDate;
    },subtractDays(date,days) {
      let newDate = new Date(date);
      newDate.setDate(this.first.getDate() - days);
      return newDate;
    },nextWeek() {
      this.first = this.addDays(this.first,7);
    },priorWeek() {
      this.first = this.subtractDays(this.first,};
</script>

<style>
.day {
  background-color: rgb(240,240,240);
  border-radius: 1rem;
  color: purple;
  display: inline-block;
  margin-left: 0.5rem;
  padding: 0.5rem;
}
</style>
,

我会先从今天的日期数组开始,然后为数组中的每个位置添加一天。您使用哪种日期库并不重要,您可以在不带任何库的Vanilla JS中使用它:

const dates = new Array(5) // start with an empty array
  .fill(new Date())        // fill in today's date everywhere
  // finally,add some time based on the position of each element
  // getTime is in milliseconds,so we need to do some multiplication
  .map((dt,i) => new Date(dt.getTime() + 1000 * 60 * 60 * 24 * i))

例如,此时的想法是相同的:

const dates = new Array(5)
  .fill(moment()) // fill with moment's this time
  // adding time to a date is more convenient in moment
  .map((m,i) => m.clone().add(i,'days'))