Calendar Component in Angular 2 Written in Typescript and Javascript

Is there a way to calculate the number of working days, excluding Saturdays and Sundays, within a specific month and year?

For example:

If we choose the year 2017 and the month of February, the output should look like this:

{
week1 : 3 days[working days]
week2 : 5 days[working days]
week3 : 5 days[working days]
week4 : 5 days[working days]
week5 : 2 days[working days]
}

Total number of working days in February 2017: 20 working days.

I am looking to accomplish this task using Angular 2 and TypeScript.

Just so you know, I am new to Angular 2 and TypeScript - consider me a beginner.

Any help would be greatly appreciated. Thanks in advance!

Answer №1

Here is a classic piece of javascript:

"use strict";

var daysOff = [0, 6],
    weekdays = ['Sun', 'Mon', 'Tues', 'Wednes', 'Thurs', 'Fri', 'Satur'];

// val represents a comma-separated month and year
// e.g.: 7,2017 or 04, 2015
// it can also be just a number (5, 9, etc.) in which case the code uses the current year
function calculateWorkingDays(val) {
    if(!val) { return false; }

    var workingCount, result = {start: null, end: null, days: []};
    val = val.split(',');

    // subtracting 1 as months are zero-based
    val[0] = parseInt(val[0]) - 1;
    if(val[0] > 11) { val[0] = val[0]%12; }

    // if year is not provided, use the current year
    if(typeof val[1] == 'undefined') {
        val[1] = new Date();
        val[1] = val[1].getFullYear();
    }

    // get the first day of the current and next month
    result.start = new Date(val[1], val[0]);
    result.end = new Date(val[1], val[0] + 1);

    // keep only the day number (0 - Sunday, ... 6 - Saturday)
    result.start = result.start.getDay();
    result.end = result.end.getDay();

    // add 28 or 35 to result.end depending on whether it's less than result.start
    if(result.end < result.start) { result.end += 7; }
    result.end += 28;

    // calculating working days
    var i = result.start;
    while(i < result.end) {
        workingCount = Math.floor(i/7);
        if(typeof result.days[workingCount] == 'undefined') { result.days[workingCount] = 0; }

        if(daysOff.indexOf(i%7) == -1) { ++result.days[workingCount]; }
        ++i;
    }

    // generating the output
    result.start = weekdays[result.start] + 'day';
    result.end = weekdays[(result.end-1)%7] + 'day';
    console.log(result);

    return result;
}

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

Inquiry regarding the TS2322 error encountered in a Svelte Component

I'm currently exploring Svelte using TypeScript. I encountered a TS23 error while working on this piece of code. <script lang="ts"> import ComponentA from './ComponentA.svelte'; import ComponentB from './Compone ...

Clicking on the <Link to=URL> in a React application built with Typescript and Redux triggers the disappearance of the component

Issue Background The application was created using npx create-react-app rrts --typescript, which sets up React, Redux, and Typescript. Problem Visualization (Content is the component with sentences) View Problem Image Here Problem Description Clicking o ...

Angular: Retain the original value of the observable

When making HTTP requests to a backend and receiving data, I use an observable stream and subscribe to it in my HTML template using async pipe. However, I am facing an issue. I need to continuously send multiple requests by clicking a button, but I want th ...

Errors encountered while trying to install the ngx-admin template through npm

After cloning the ngx-admin angular template from the git repository located at https://github.com/akveo/ngx-admin, I encountered a series of errors when trying to install the node modules and run the project: npm ERR! code 1 npm ERR! path C:\Users&bs ...

Encountering Error ENOENT while running Gulp Build Task with SystemJS in Angular 4

UPDATE: 2020.02.13 - It seems like another individual encountered the same issue, but no solution was found. Check out Github for more details. An array of GulpJS errors is emerging when attempting to construct an Angular 4 Web App with SystemJS. The str ...

Can anyone tell me the best way to access the name attribute of an HTML element in TypeScript?

Currently, my code is utilizing the name attribute to verify whether the user has entered information in a specific field and validating the input. However, I am facing an issue where the submit button remains active even if there are empty fields presen ...

Trouble with displaying ChartsJS Legend in Angular11

Despite thoroughly researching various documentation and Stack Overflow posts on the topic, I'm still encountering an odd issue. The problem is that the Legend for ChartsJS (the regular JavaScript library, not the Angular-specific one) isn't appe ...

Exploring Expression Wrapping in Angular/Typescript: Seeking clarification on the guidelines for knowing when and where it is necessary

Can someone please explain to me the concept of "expression wrapping" in TypeScript and when it is needed? For example, why are the parentheses used in <[Parent, (Children[])]>? If I define a tuple type and use it in the resolve method signatur ...

Is there a way to modify the login component to utilize the username instead of the email for logging in?

I recently developed a Spring Boot API which requires the username and password for login authentication. I am now trying to modify the ngx admin interface to accept the username instead of the email as the credential. Can anyone provide guidance on how ...

Determination of function return type based on the presence of an optional argument

I am attempting to design a function that will have a return type based on whether an optional parameter (factory) is provided or not If the factory parameter is passed, then the return type should match the return type of the factory Otherwise, it shoul ...

Is there a way to programmatically update the values of Primeng Turbotable's ReorderableColumns and ResizableColumns from a component

The properties resizableColumns and reorderableColumns have default values of 'true'. What I am attempting to do is fetch 'true' or 'false' from an initdata file in the ngOnInit() method, and then set these initial values to t ...

What causes Node.js to crash with the Headers already sent Error while managing errors in Express?

My current project involves using Express to set up an API endpoint for user registration. However, I've encountered a problem where sending a request that triggers an error to this API endpoint causes my node.js server to crash. The specific message ...

Creating instances of a child class in Typescript using a static method in the parent class, passing arguments and accessing other static methods

Struggling with instantiating a child class from a static method in a base class. Looking to properly specify the return type instead of resorting to using any for all static methods. Tried a solution here, but it falls short when dealing with static metho ...

Creating a TypeScript schema with nested maps and arrays using Dynamoose

I'm currently in the process of developing a schema for a specific example: { "foods": [ { "fruits": [{ "apple": { "color": "red", ...

How to Retrieve ViewChild Element from within Input Component in Angular 2

Currently, I am utilizing ViewChild to target a specific HTML element within an Angular 2 component. My goal is to access this element from an Input field, but I am struggling with the correct syntax to correctly target the element in question. Below is th ...

Weighing the importance of a multiple-choice quiz

I am faced with the challenge of assessing 25 multiple choice questions, each offering 4 answer choices worth varying points. Additionally, I have 2 free response questions that I wish to score based on the time taken to answer them. My proposed scoring ru ...

Using a Class Decorator in Typescript to Enhance Static Methods across all Classes

Imagine having a class filled with numerous static methods. The objective is to encapsulate each static method within a function. The specific aim is to handle async errors by applying .catch to every static method in the following manner: // Within user-r ...

What is the best way to customize the hover-over label appearance for a time series in ChartJS?

In my Angular 8 setup, I am working with the 'Date' data type and configuring multiple datasets of a 'Cartesian' type. I have been referring to documentation from here for guidance. Despite setting up the X Axis using callbacks in my co ...

No errors are being displayed with the React Hook Form using Zod and Material UI

Presenting my custom ProductInfoForm built using Material UI, react-hook-form with zod validations. However, I am encountering an issue: upon submitting the form, the data is displayed in the console as expected, but when intentionally triggering an error, ...

having difficulties in separating the mat-table header

It may seem like a basic question, but I'm having trouble figuring it out. I'm not sure if this requires a CSS change or something else. I'm looking to add a divider between my table header similar to the one highlighted in the screenshot be ...