Discover the process of retrieving all workday dates using Angular

Currently, I am working on a project in Angular that involves allowing employees to record their work hours. However, I am facing a challenge in figuring out how to gather all the work dates and store them in an array. Here is what I have attempted so far:

getDaysInMonth(month, year) {
    this.date = new Date(Date.UTC(year, month,));
    this.days = [];
    while (this.date.getMonth() === month) {
      if(this.date.getDay() == 6 || this.date.getDay() == 0) {
        return "weekend";
      }
      this.days.push(new Date(this.date));
      this.date.setDate(this.date.getDate() + 1);
    }
    return this.days;
}

Answer №1

The issue lies in the current implementation where "weekend" is returned from the if statement, causing the function to exit once a weekend day is encountered. This updated snippet addresses the problem:

getDaysInMonth(month, year) {
  this.date = new Date(Date.UTC(year, month));
  this.days = [];
  while (this.date.getMonth() === month) {
    this.date.setDate(this.date.getDate() + 1);
    if(this.date.getDay() == 6 || this.date.getDay() == 0) 
      continue;
     this.days.push(new Date(this.date));
  }
  return this.days;
}

Answer №2

If you need to generate a list of working days for a specific month and year, the code below can help you achieve that.

function findWorkingDays(startDate, endDate) {
     var workingDates = [];

    var currentDate = startDate;
    while (currentDate <= endDate)  {  
        var weekDay = currentDate.getDay();
        if(weekDay != 0 && weekDay != 6){
            workingDates.push(currentDate.getDate());
        }

         currentDate.setDate(currentDate.getDate()+1); 
    }

    return workingDates;
 }


function getDaysInMonth(month, year) {
     var start = new Date(month + '/01/' + year);
     var end = new Date(start.getFullYear(), start.getMonth() + 1, 0);

     console.log(findWorkingDays(start, end));
}

getDaysInMonth(11, 2019);

Answer №3

If you use a return statement in your code, it will end the execution of both the while loop and the method entirely. To only break out of the current iteration of the while loop and move on to the next one, simply substitute continue;.

Answer №4

Check out this code snippet that I crafted during a recent project - it might just be the solution you're looking for:

function calculateWorkingDays(startDate, endDate) {
    startDate = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate());
    endDate = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate());
    
    let days = 0;
    let currentDate = startDate;
    
    while (currentDate <= endDate) {
        const dayOfWeek = currentDate.getDay();
        
        if ((dayOfWeek !== 6) && (dayOfWeek !== 0)) {
            days++;
        }
        
        currentDate.setDate(currentDate.getDate() + 1);
    }

    return days;
}

calculateWorkingDays(new Date("01.10.2019"), new Date("31.10.2019"));

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

Tips for transferring the output of a JavaScript async function to a Python variable

var = driver.execute_script("setTimeout(function(){ return [1,2,3]; }, 1000);") Utilizing the Selenium method execute_script, I am attempting to extract data from a website using javascript and assign it to a python variable var. The challenge a ...

What is the appropriate event type to pass to the onKeyPressed function in a React application utilizing MaterialUI and written with Typescript?

I am currently working on a React application using Typescript and MaterialUI, where I have implemented a TextField component. My goal is to capture the value of the input HTML element when the user presses the enter key. To achieve this, I have created ...

Sending information from service.ts to component

I'm encountering a roadblock with this issue, hopefully I can find some assistance here. Essentially, I am attempting to make a simple get http request in http.service and then pass the json object to the filter.service. From there, I aim to transfer ...

Retrieving a subset of JSON data from a larger JSON object in a Node.js environment

I'm working with a JSON object structured like this: [ { "id": "458712e247328e4ebfafeb4d922b", "value": [ 1 ], "location": null, "metadata": null, "at": "2015-07-16T16:33:39.113Z" }, { "id": "1ghj78d8220734c00ab941 ...

What is the best way to adjust the size of a canvas and then upload the resized information to a

I need to update the user's database table row data with new resized dimensions (changing width and height). For instance: In my online editor, I create a canvas of size 1000x500, add objects, and save -> This data is sent to the database When re ...

Trouble with CSS transitions not functioning while altering React state

Each time a user clicks on an accordion, the content should smoothly show or hide with a transition effect. However, the transition only seems to work when opening a closed accordion, not when closing an already open one! To get a clearer idea of this iss ...

NodeJS API integration failure during ReactJs login attempt

Currently, I am tackling a small project on implementing user login functionality in ReactJs with Nodejs and Express-session. The issue I am facing is that my front end (React login page) isn't functioning properly. Below is the Fetch API code snippet ...

Determine if the object's value is present

My current JavaScript setup looks like this: var NAMES = []; function INFO(id,first,middle,last){ var newMap = {}; newMap[id] = [first, middle, last]; return newMap ; } Next, I have the following code block: for (var j = 0; j < NUMBER.leng ...

Refreshing a page in Angular 4/5 using TypeScript

I am currently working on a single-page application that utilizes routes for navigation: this.router.navigate(['/customer-home'], { skipLocationChange: true }); While on the customer home page, I have a feature to add a new customer via a REST ...

Switch up a font style using JavaScript to apply a Google font effect

I am attempting to implement a discreet hidden button on a website that triggers a unique Google font effect for all of the h1 elements displayed on the page. However, I am uncertain about the process and unsure if it is achievable. Below is the code snipp ...

Toggle the sliding menu drawer option (upward/downward motion)

When it comes to my simple menu, I'm using jQuery to toggle the visibility of a few DIVs. The code is straightforward as shown below, and I could really use some assistance with adding extra functionalities. <div id="one" class="navLinks"> cont ...

The jQuery ajax function is not properly displaying or hiding the loader div

While attempting to call PHP code using a jQuery AJAX function, I encountered an issue where I wanted to display a loader div while the request was being sent and then hide the div once the request was complete. To simulate this scenario, I deliberately de ...

Implementing jQuery slideDown effect on a nested table element

I am facing an issue where the nested table does not slide down from the top as intended when a user clicks the "Show" button. Despite setting the animation duration to 500ms with jQuery's slideDown() function, the table instantly appears. I am using ...

Guide on how to bypass IDM when downloading a PDF file through a GET request

When I try to fetch a PDF by sending a GET request to the server and open it in a new tab, IDM interrupts my request and downloads the file instead. It changes the server response status to 204 and removes the headers. How can I prevent IDM from doing th ...

Create original identifiers for dynamically generated material

I have developed a custom invoice tool that has the capability to dynamically add rows. Here is the code snippet responsible for generating new rows: $("#addrow").click(function(){ $(".item-row:last").after('<tr class="item-row"><td> ...

Updating dynamic parameter in a NextJS 13 application router: A complete guide

In my route user/[userId]/forms, I have a layout.tsx that includes a Select/Dropdown menu. The dropdown menu has options with values representing different form IDs. When the user selects an item from the dropdown, I want to navigate to user/[userId]/form ...

React.memo is failing to stop unnecessary re-renders of a stateless functional child component that does not receive any props

There is a stateless functional component known as Title, which utilizes React-Reveal to showcase simple heading elements upon rendering. Despite having no internal state and not receiving any props from its parent component (GameHeader), the issue arises ...

How to modify the color of a div element with jQuery?

I need some help changing the color of a div with 'jQuery', but I am not sure how to do it. Below is the code I have been trying: function updateDivColor() { $('#OutlineX1').css("color","blue"); } ...

The updated version of Angular from 13 to 16 has implemented a new default value for primary colors

I recently upgraded my angular (+material-ui) system from version 13 to 16, and encountered an issue with the primary color of my custom theme. It seems that the value is no longer being recognized and defaults to blue. After updating the angular version, ...

Tips for showcasing the popover content on a separate page?

Whenever I click on "Choose City," a popover will appear containing two cities: 'Bengaluru' and 'Hyderabad.' If I select Bengaluru, the city name should be displayed instead of "Choose City." home.html: <ion-header> <button ...