显示 Angular 中的当前工作日日期

Displaying Current Weekdays dates in Angular

如何在 Angular 中显示当前工作日日期?这是 table 和 Mon-Fri 的时间,我想动态显示 运行 周的具体日期。

例如本周从 2021 年 3 月 1 日开始。所以想在 table header 中显示如下 -

Mon             Tues          Wed            Thur            Fri
01/03/2021      02/03/2021    03/03/2021     04/03/2021      05/03/2021

当本周更改为下周时,日期应动态更改为该周。

你可以只使用 DatePipe

比如说,在 .ts 文件中我有一个像这样的字段日期:

    date: Date = new Date(Date.now());

然后我可以像这样使用管道在 HTML 中获取工作日:

    {{ date | date:'EEEE' }}

好的,第二次尝试,现在我明白你的问题了:)

首先,我想指出有许多可用的日历和日期选择器组件(如 Bootstrap one),但如果您只是想将日期显示为 table header, 我又要了一个日期变量:

    startOfTheWeek: Date = new Date("2021-03-01");

这是您要显示的一周的开始日期。当然这应该是动态的,也许看到那部分的JavaScript - get the first day of the week from current date。假设我们有我们想要的星期一,我写了一个 lillte 辅助函数:

    public getWeekDays(startingDate: Date): Date[] {
      const dateList: Date[] = [];
      for (let i = 0; i <= 4; i++) {
        const newDate = new Date(this.startOfTheWeek.getTime());
        newDate.setDate(newDate.getDate() + i);
        dateList.push(newDate);
      }
      return dateList;
    }

我只是创建了一个包含 5 个日期的数组,其中每个日期都比前一个日期多一天。

在模板中我会做这样的事情:

    <table>
      <thead>
        <tr>
          <th *ngFor="let day of getWeekDays(startOfTheWeek)">{{day | date:"EEE'\n'd/M/y"}}</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>running</td>
          <td>running</td>
          <td>running</td>
          <td>running</td>
          <td>running</td>
        </tr>
      </tbody>
    </table>

有了这个CSS:

    table, tr, th, td {
      border: 1px solid black;
    }

    th {
      white-space: pre-wrap;
    }

pre-wrap是为了保留日期和工作日之间的换行。

希望对您有所帮助:)

我可以用 moment.js

来解决