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

The Chrome application does not retain cookies

Why is the cookie url_user not being stored? Below is the content of index.html: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial- ...

Move information from one page to another

I'm currently using Ionic 2 and attempting to pass data from one page to another. Specifically, I want to transfer the data of a selected list item from the first page (quickSearch) to the second page (quickSearchDetail). To illustrate this, refer to ...

Displaying a loading animation to keep users engaged while AJAX calls retrieve data from the server

My issue was outlined in a recent discussion on Stack Overflow. In essence, my goal is to display a loading indicator before server-side processes complete: [Loader] -> [Target page]. However, the HTML content loads after the server-side tasks, resultin ...

Is there a JavaScript toolkit specifically designed for animating mobile devices?

Currently in search of a JavaScript Library that is similar to impress.js, allowing me to create dynamic animations on text content that are compatible with iOS/Android. Although Hype by Tumult seems promising, I am not interested in an editor but rather ...

While trying to install express using Node.js, an error (error:0906D06C :PEM routines : PEM_read_bio npm) occurred

I recently installed node.js on my computer and npm came along with it. However, when I try to execute "npm install express" in my Windows command prompt, I encounter the following error message. Can anyone guide me on how to resolve this issue? C:\U ...

Leverage the sync function within the await .then("sync") method in JavaScript

If a synchronous function is called within the .then part of an asynchronous await .then, such as: await asyncFunc(...) .then(res => sendMSG(res)) .catch(err => next(err)); function sendMSG(res){ xyz } The sync function sendMSG i ...

create a division in the organization of the identification numbers

Is there a way to always change pages when the id changes in a foreach loop to separate the printed pages? Take a look at this code snippet: var data = [ {Id: "552", valor: "50.00", Descricao: "Fraldas", }, {Id: "552", valor: "35.00", Descrica ...

Learn the process of uploading an image to Firebase storage from the server side

I'm working on implementing an upload feature that utilizes Firebase storage on the server side. Here is the upload function on the server side: const functions = require("firebase-functions"); const admin = require("firebase-admin&quo ...

Attempting to create a promise for a dropdown menu in React-Select

I am facing an issue here: type Person = { value: string; label: string; }; Furthermore, I have a promise-containing code block that fetches data from an API and transforms it into the appropriate array type for a React component. My intention is to r ...

Tips on using Bootstrap 4 containers within a container-fluid and ensuring text stays within a container at all times

What is the best way to incorporate a Bootstrap 4 container within a container-fluid? how can we ensure that text is always contained within the blue section? ...

Angular 2 Issue: @Input() Directive Not Recognized - Unresolved Reference Error

I am a beginner trying to grasp Angular2 concepts from ng-book 2(v49). Below is the code snippet from article.componenets.ts file: import { Component, OnInit } from '@angular/core'; import { Article } from './article.model'; @Componen ...

Error message: Parameters are not defined in the Next.js

Struggling to retrieve the endpoint from a specific page in my Next.js application using URL parameters. Despite being able to view the endpoint in the browser, it keeps returning as undefined. I attempted utilizing usePathname from next/navigation, which ...

Error message: Unspecified service injected

I am currently working with 2 separate javascript files for my project. One is being used as a controller, while the other serves as a service. However, when I attempt to inject the service into the controller and access its function, an error message pops ...

Tips for controlling or concealing slot elements within child components in Vue Js

I'm working with a named slot: <div name="checkAnswer" class="w-[70%] mx-[15%] flex items-center justify-center" > <button class="p-3 rounded-3xl shadow-md font-bold m-4 px-10 border-2 bo ...

Encountered a style group error 'non-collision' while using Angular with HERE Maps JS API 3.1

Occasionally, I encounter an error when trying to load a HERE map with the satellite base layer: Tangram [error]: Error for style group 'non-collision' for tile 13/16/15542/12554/15 Cannot read property 'retain' of undefined: TypeE ...

Incorporating and designing a side button using jQuery Mobile

I'm working on adding a button to the left side of the screen that is round (but not necessarily) and partially visible, with a visually appealing design. This button will allow users to open a side menu panel. Below is the HTML code for the button: ...

Preventing page reload by using event.preventDefault() does not work with Ajax Form

I've been working on a code snippet to submit a form using Ajax without any page reloads: $( document ).on('submit', '.login_form', function( event ){ event.preventDefault(); var $this = $(this); $.ajax({ data: ...

Is there a way to target a sibling element of another element by using its identifier in Cypress?

My current task involves clicking a checkbox within a list of table rows. The only way I can think of reaching this level is by targeting the span tag along with its corresponding name. cy.get('tr > td > span').contains('newCypressTes ...

Error encountered while upgrading to Angular 5: splitHash issue

Currently in the process of transitioning from Angular 4.x to 5.x, I have encountered the following error: main.81bcdf404dc22078865d.bundle.js:1 Uncaught TypeError: i.splitHash is not a function at Object.t.parseUrl (main.81bcdf404dc22078865d.bundle.js:1) ...

Tips for utilizing ng-repeat with a function that generates a fresh object?

My HTML code includes the following element: <button ng-click="console.log(key)" ng-repeat="(key, value) in getLocalStorageKeys() track by $index"> In my JavaScript file, I have the following function: $scope.getLocalStorageKeys = function(){ ...