Sz2013
Sz2013

Reputation: 366

Displaying Current Weekdays dates in Angular

How do I display the current weekdays dates in Angular? This is for a timetable with Mon-Fri , and I would like to display the specific dates for the running week dynamically.

For example this week is commencing from 1st march 2021. so want to display in table header as below -

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

When the week changes to next week, dates should change to that week dynamically.

Upvotes: 1

Views: 3397

Answers (3)

Sz2013
Sz2013

Reputation: 366

I could solve it using moment.js

Upvotes: 1

Jannis Adamek
Jannis Adamek

Reputation: 51

OK, the second try, now I get your question :)

First I'd like to note that there are many calendar and Datepicker components available (like the Bootstrap one) but if you simply want to show the date as a table header, I'd just have a date variable again:

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

which is the starting day of the week you want to display. Of course this should be dynamic, maybe see JavaScript - get the first day of the week from current date for that part. Assuming we have the Monday we want, I wrote a lillte helper function:

    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;
    }

I just create an array with 5 dates, where each date has one day more than the previous one.

In the template I'd do something like this:

    <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>

With this CSS:

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

    th {
      white-space: pre-wrap;
    }

pre-wrap is to preserve the newline between the date and the weekday.

Hope that helps :)

Upvotes: 1

Jannis Adamek
Jannis Adamek

Reputation: 51

You can just use DatePipe for that.

Say, in the .ts file I have a field date like so:

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

Then I can get the weekday in the HTML with the pipe like so:

    {{ date | date:'EEEE' }}

Upvotes: 2

Related Questions