Time grid - powered by momentjs and typescript

https://i.sstatic.net/Xzggb.png

Welcome! If you're looking to add a day picker in a calendar, keep reading for my solution.

Answer №1

The function takes the year and month as input and generates a matrix of [weeks][days] to construct a calendar view.

private generateMonthCalendar(year: number, month: number) : Moment[][]
{
    const startDate: Moment = moment({ year: this.model.actualYear, month: this.model.actualMonth }).startOf('month');  //first day of month
    const endDay: Moment = moment(startDate).add(1, 'month').add(-1, 'day'); // last day of month

    // Determine the weeks to display from the first day to the last day of the month
    const weeks: Dictionary<string, { week, year }> = new Dictionary();
    for (let day: Moment = moment(startDate); endDay.diff(day) >= 0; day.add(1, 'day'))
    {
        let key = day.isoWeekYear() + "_" + day.isoWeek();
        if (!weeks.containsKey(key))
        {
            weeks.setValue(key, { week: day.isoWeek(), year: day.isoWeekYear() });
        }
    }

    // Construct the calendar
    var calendar = [];
    weeks.forEach((index, week) =>
    {
        // Get seven days for every week
        var weekDays = [];
        for (var d = 1; d <= 7; d++)
        {
            weekDays.push(moment().isoWeekYear(week.year).isoWeek(week.week).day(d));
        }
        calendar.push(weekDays);
    });
    return calendar;
}

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

Angular 12: TypeScript Issue TS2339 - Unable to Locate Property on Type

Whenever I use the code below, I encounter error TS2339: Property 'timestamp' does not exist on type 'LogRepair[]' In the component's HTML file, I am attempting to loop through an array of properties defined in the LogRepair typ ...

The Lenis smooth scrolling feature (GSAP) is not functioning properly

I have encountered an issue with the smooth scrolling feature of gsap causing a delay on my website. This problem is only resolved when I manually go into the browser settings and disable smooth scrolling by navigating to chrome://flags/#smooth-scrolling ...

Struggling with sluggish performance on a certain project within VS Code

My experience with VS code has been excellent over the years, but I recently encountered a problem in one of my projects that caused a significant slowdown in performance. Strangely, other projects are working fine without any issues on VS code. I suspect ...

Utilizando Typescript com Ionic 2 e AngularJS para autenticar através de um método de post na requisição HTTP e

Greetings and good afternoon to everyone. I hope you all are doing well. I am a beginner in AngularJS, currently using Visual Studio, Ionic 2, and TypeScript. I have successfully connected my app to a REST API in .NET and have implemented a token for tes ...

Retrieving data from an Angular 5 Input text field

I have been struggling with what seems like a simple question, but none of the solutions I found seem to work for me. In my component.html file, I have a standard input field: <div class="form-group"> <label>Serial</label> <in ...

Creating an instance of a class using a class decorator, with or without the 'new'

Seeking alternatives to creating class instances without using the new keyword in TypeScript, I came across this excellent solution that works seamlessly in JavaScript. The code found in the repository mentioned https://github.com/digital-flowers/classy- ...

Determine if a Matrix is Invertible: Guide to Eigen

I'm looking to create a randomly generated invertible matrix using Eigen that meets the following criteria: Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> res(M, N + 1); Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> y(M, 1); y.setRand ...

Why does TypeScript struggle to accurately deduce the return type when provided with certain parameter values?

I have a function that uses a switch case to return different results depending on the input. The function, called "getTimeAgo," takes in two parameters: "date" (which can be either a Date object or a string) and "mode" (which can only be either "days" or ...

Using Typescript to pass inferred type to React's useCallback

Illustration: function useFunction(fn) { return fn; } type Data = { '/person': { person: any }, '/place': { place: any }, }; function useData<Path extends keyof Data>( path: Path, options: { callback?: (data: Data[ ...

There is no value stored in the Angular BehaviorSubject

My attempt at creating a web-socket-client involved organizing all server messages into a BehaviorSubject. Here's the snippet of code: export class WebSocketConnectionService { public ResponseList: BehaviorSubject<WebSocketResponse> = new Be ...

RxJs will only consider the initial occurrence of a specific type of value and ignore any subsequent occurrences until a different type of value is encountered

I'm faced with a situation where I need to extract the first occurrence of a specific value type, followed by the next unique value of a different type. Let's break it down with an example: of(1,1,1,1,2,3,4) .pipe( // some operators ) .subsc ...

Retrieving information from a Kendo grid cell

I am working on a web application that utilizes Kendo Grid. How can I retrieve the values of the "Ticket No" from the selected checkboxes? https://i.stack.imgur.com/aPOje.png This is my code: var grid = $("#poGrid").data("kendoGrid"); grid.items().filte ...

Incorporating TypeScript's internal references

I am currently working on defining my own model interface that extends the Sequelize model instance. However, I am encountering difficulties in referencing the Sequelize interface within my code. Specifically, I receive an error stating "Cannot find name ...

When a MatFormFieldControl both implements ControlValueAccessor and Validator, it can potentially lead to a cyclic

I am attempting to develop a custom form control by implementing MatFormFieldControl, ControlValueAccessor, and Validator interfaces. However, I encounter issues when including NG_VALUE_ACCESSOR or NG_VALIDATORS. @Component({ selector: 'fe-phone-n ...

What are the signs that indicate whether a parameter is an enum or an array of enums?

I am looking to pass either a single enum value or an array of enum values to a function. In order to achieve this, I have created a custom function: export enum SettingType { hairColors ='haircolors', hatSizes = 'hatsizes' } publi ...

Having trouble consuming data from a service in Angular 6?

I'm in the process of creating a basic cache service in Angular; a service that includes a simple setter/getter function for different components to access data from. Unfortunately, when attempting to subscribe to this service to retrieve the data, t ...

Customizing Material UI Select for background and focus colors

I am looking to customize the appearance of the select component by changing the background color to "grey", as well as adjusting the label and border colors from blue to a different color when clicking on the select box. Can anyone assist me with this? B ...

Sharing information between sibling modules

Currently, I am faced with the challenge of transmitting data between two sibling components within the following component structure. The goal is to pass data without changing the relationships between these components. I prefer not to alter the componen ...

Trouble securing an undefined value in a union type

Encountering an error with the code below that seems unexpected. TypeScript is flagging rules[name] as not being callable, which is true since it can be undefined. Even after guarding against this case, the same error persists. The issue is elaborated in t ...

Struggling with setting up the onChange function in a Next.js application

After successfully writing and testing the code here, I encountered an error preventing me from building it. Please review the code for any issues. I am attempting to set onChange to handle user input in a text field. Currently using onChange={onChange}, ...