Angular date selection with a range of plus two days, factoring in the exclusion of weekends

I am currently using a mat date picker range with specific logic. The minimum date that a user can select on the calendar is set to + 2 days. For example, if today's date is July 20, 2022, the minimum selectable date would be July 22, 2022.

However, if the next 2 days after the current date fall on weekends, they should be excluded from selection. For instance, if today is July 22, 2022 and the following two days (July 23 and July 24) are weekends, then the new minimum selectable date should start from July 22, 2022, skipping the weekend days, and extend to July 25, 2022, making the new minimum date July 26, 2022.

I am looking for suggestions on how to implement this logic in a date picker.

#https://stackblitz.com/edit/angular-byrmnt-setsza?file=src%2Fapp%2Fdate-range-picker-overview-example.ts,src%2Findex.html,src%2Fapp%2Fdate-range-picker-overview-example.html

#html

<mat-form-field>
  <mat-label>Enter a date range</mat-label>
  <mat-date-range-input [rangePicker]="picker" [dateFilter]="weekendsDatesFilter">
    <input matStartDate matInput placeholder="Start date" >
    <input matEndDate matInput placeholder="End date">
  </mat-date-range-input>
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>

#ts

export class DateRangePickerOverviewExample {
  currentDate = new Date();

  ngOnInit(): void { 
    this.currentDate = new Date(this.currentDate.setDate(this.currentDate.getDate() + 2));
  }

  weekendsDatesFilter = (d: Date): boolean => {
    const day = d.getDay();
    /* Prevent Saturday and Sunday for select. */
    return day !== 0 && day !== 6;
  };
}

Answer №1

Would you mind verifying this clicking here? Hopefully, it will meet your needs.

 import { Component } from '@angular/core';
    
    @Component({
      selector: 'date-range-picker-overview-example',
      templateUrl: 'date-range-picker-overview-example.html',
      styleUrls: ['date-range-picker-overview-example.css'],
    })
    export class DateRangePickerOverviewExample {
      currentDate = new Date();
    
      ngOnInit(): void {
        this.currentDate = new Date(
          this.currentDate.setDate(this.currentDate.getDate() + 2)
        );
        !this.weekendsDatesFilter(this.currentDate) && this.weekendsHandler();
      }
    
      weekendsDatesFilter = (d: Date): boolean => {
        const day = d.getDay();
        /* Avoid selecting Saturdays and Sundays. */
        return day !== 0 && day !== 6;
      };
      weekendsHandler() {
        this.currentDate = new Date(
          this.currentDate.setDate(this.currentDate.getDate() + 3)
        );
        !this.weekendsDatesFilter(this.currentDate) && this.weekendsHandler();
      }
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble mocking Node fs Modules using Sinon

I am facing an issue with mocking the promises methods of the node fs module in my code. When my appData.ts file is executed, it calls the actual fs.promises.mkdir method instead of the mock function defined in \__tests__/appData.test.js. I suspect ...

Retrieve all users using Auth0 with Angular 2

I am trying to retrieve all users from auth0 using angular2 by following the documentation provided at https://auth0.com/docs/api/management/v2#!/Users/get_users. Here is what I have attempted so far. I understand that I need to include the access token, ...

The Vue.JS application encountered an error while making an API request, resulting in an uncaught TypeError: Cannot read properties of undefined related to the 'quote'

<template> <article class="message is-warning"> <div class="message-header"> <span>Code Examples</span> </div> <div class="message-body"> ...

Transforming Form Input into Request Payload for an AJAX Call

I'm facing a challenge in submitting my form data through a POST AJAX request and haven't been able to come across any solutions so far. Due to the dynamic creation of the form based on database content, I can't simply fetch the values usin ...

I am looking to create a div that can consistently refresh on its own without needing to refresh

I have implemented a comment system using ajax that is functioning well. I am looking to incorporate an ajax/js code to automatically refresh my "time ago" div every 5 seconds so that the time updates while users are viewing the same post. Important note: ...

Tips for exchanging JavaScript variables with PHP using AJAX

Hey there, I'm new to JavaScript and I've hit a roadblock with passing variables to PHP using Ajax. <script> $date = "123"; $.ajax({ url: './record.php', type: "POST", ...

Angular's Async Pipe displaying outdated data

I am encountering an issue with my Angular async pipe setup. Here is the code snippet: <ng-container *ngIf="showProjects && (projects | async) as projectList; else loading"> In my projects.page.ts file, I have the following funct ...

I noticed that my jquery code is injecting extra white space into my HTML5 video

Ensuring my HTML5 background video stays centred, full-screen, and aligned properly has been made possible with this jQuery snippet. $(document).ready(function() { var $win = $(window), $video = $('#full-video'), $videoWrapper = $video. ...

React- The Autocomplete/Textfield component is not displaying properly because it has exceeded the maximum update depth limit

My autocomplete field is not displaying on the page even though I wrapped it with react-hook-form for form control. When I check the console, I see this error: index.js:1 Warning: Maximum update depth exceeded. This can happen when a component calls setSt ...

Using PHP to set cookies after making an AJAX request

After reviewing numerous posts on this topic, I am still unable to set any cookies with my code. The initial ajax call in my code looks like this: $("#loginForm").submit(function(event) { event.preventDefault(); var uid = document.getElementById( ...

What is the best way to enable import and require support for npm modules?

Recently, I successfully published my debut module on npm using Javascript. Now, I am eager to ensure that it can support both import and require functions. Can someone guide me on how to achieve this? For reference, the module in question is available at ...

The blur() function in -webkit-filter does not seem to function properly in Vue.js

I'm having trouble implementing the -webkit-filter: blur() property. I tried using "filter" instead, but it still isn't working. Could this be a limitation of Vue.js or are there any other solutions available? <template> <div class=&qu ...

Using TypeScript to create a generic function that returns a null value

In my Typescript code, I have the following function: In C#, you can use default(T), but I'm not sure what the equivalent is in Typescript. public Base { ... } public Get<T extends Base>(cultura: string): T[] { let res = null; try ...

How to use JavaScript regular expressions to extract the content following the second-to-last occurrence of a back

I currently have a regular expression that looks like this: /^.*[\\\/]/ At the moment, it removes every single backslash from a string. However, now I need to modify it in order to capture everything after the second to last backslash. Fo ...

Using JavaScript, divide a string containing elements of unknown length that may be adjacent based on their type

If I have a string representing an SVG path like: "M72 0v754h405v-86h-311v-211h302v-86h-302v-285h311v-86h-405z" My goal is to transform it into an array where each element consists of either a letter or a positive/negative number. For example: [ ...

Issue encountered when trying to import an image URL as a background in CSS using Webpack

I have been trying to add a background image to my section in my SCSS file. The linear gradient is meant to darken the image, and I'm confident that the URL is correct. background-image: url(../../assets/img/hero-bg.jpg), linear-gradient(r ...

Tips on sending the total value of a form to a PHP script

Looking for help with a PHP script to calculate the sum of checked checkboxes with corresponding numeric values. For example, if checkbox 1 = 80; checkbox 2 = 21; and checkbox 3 = 15, and the user checks checkboxes 2 and 3, the PHP should output 36. I hav ...

Navigating a collection of objects after a button is clicked

My current library project involves looping through an array of objects to display them on a grid based on input values. Here is the code snippet for my loop: const addBook = (ev) => { ev.preventDefault(); let myLibrary = []; let bookIn ...

Configuring CORS in an Angular JS controller

Having a controller with a service that retrieves JSON from another server, I encountered the following issue: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http:somesite.com. This can be fixed by moving the ...

Link together a series of AJAX requests with intervals and share data between them

I am currently developing a method to execute a series of 3 ajax calls for each variable in an array of data with a delay between each call. After referring to this response, I am attempting to modify the code to achieve the following: Introduce a del ...