generate a neatly organized schedule of time slots for presentation

Looking to generate a list of selectable times in 24-hour format for users to choose from. Here's an example:

Begin with: 01:00 AM 01:30 AM 02:00 AM ...

End with: 11:30 PM 00:00 AM 00:30 AM ...

Although I've tried the method below, I'm unable to achieve the desired result:

  buildInitialHours() {

    const hourList: any[] = [];
    let hourObj = { hour: 0, minute: 0, label: '' };

    for (let count = 0; count < 48; count++) {
      hourObj.hour += 1;
      hourObj.minute += 30;
      hourObj.minute = hourObj.minute == 60 ? 30 : 30;
      hourObj.label = `${hourObj.hour}:${hourObj.minute}`;
      hourList.push(Object.assign({}, hourObj));
    }

    this.initialHours = hourList;
  }

Answer №1

Another option is to fill the list with dates and then employ the angular date pipe to format them for display. Utilize date-fns or moment to manipulate the dates accordingly.

Answer №2

This is how I resolved the issue:

  createInitialHoursList() {

    let hoursList: Date[] = [];
    const currentDate = moment();

    for (let i = 0; i < 48; i++) {
      let lastHour = hoursList[hoursList.length - 1];

      if (!lastHour) {
        currentDate.set({ hour: 0, minute: 0, seconds: 0 });
        hoursList.push(currentDate.toDate());
        continue;
      }

      const newHour = lastHour.getMinutes() == 30 ? lastHour.getHours() + 1 : lastHour.getHours();
      const newMinutes = lastHour.getMinutes() == 0 ? 30 : 0;
      const timeObject = { hour: newHour, minutes: newMinutes, seconds: 0 };
      lastHour = moment(lastHour).set(timeObject).toDate();
      hoursList.push(lastHour);

    }

    this.initialHoursList = hoursList;
  }

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

What is the best way to verify a numerical input in a React component?

When I use the return statement, I attempt to validate a number and if it's not valid, assign a value of 0. However, this approach doesn't seem to be working for me. Is there an alternative method to achieve this? return ( <Input col ...

TypeScript's conditional property failing to recognize incorrect functional argument

The concept of a conditional type should encompass smart properties, and I sought assistance from @jcalz in the previous iteration of this query. Even though that issue was resolved, I am still unable to achieve the level of typing strictness I desire. The ...

What is the proper way to bring in Typescript types from the ebay-api third-party library?

My TypeScript code looks like this: import type { CoreItem } from 'ebay-api'; declare interface Props { item: CoreItem; } export default function Item({ item }: Props) { // <snip> } However, I encounter an issue when trying to build ...

Avoid incorporating unicode characters in Angular 4

How can I prevent users from using unicode characters in a text field in my front-end developed with Angular 4 framework? For example: ½ -> U+00BD ('onehalf') ...

Is it possible to utilize a TypeScript type in conjunction with io-ts?

Currently, I am in the process of validating API responses with io-ts. In my TypeScript setup, I have already defined the following data structure: export type Group = { id: number; name: string; } Now, my objective is to incorporate this type into ...

Uploading files using Remix.run: Transforming a File object into a string during the action

I'm currently developing a Remix application that allows users to upload files through a form. I have a handler function for handling the form submission, which takes all the form data, including file attachments, and sends it to my action. The probl ...

There appears to be a problem with the syntax in the JSON data at position 0, as it is detecting

WARNING: core.es5.js?0445:1084 WARNING SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous> SCENARIO: The goal is to automatically select the option that the user previously chose and prevent them from voting twi ...

Rendering a component in React based on multiple conditions

Checking sessionStorage and another state variable before rendering a component is essential for my application. I want to avoid showing the same message multiple times within the same session. This is how I have implemented it: const addSession = (noteId: ...

Tips for troubleshooting the 404 error on nginx servers

I've got an angular 4 Single Page Application (SPA) and I'm using Docker for production. Everything seems to be going smoothly so far. When I navigate to the /dist folder in the terminal, I use the following command to point docker to the content ...

What is the process of converting an Array that is nested within an Object?

I am facing compile errors while attempting to convert an Object containing an Array of Objects. Here is the initial structure: export interface CourseRaw { metaInfo: MetaInfoRaw; gameCode: number; gameText: string; images?: ImageRaw[]; // Having ...

mat-select-country - encountering difficulty in defining default selection

I have implemented the mat-select-country component to display a list of countries and allow users to select one. <mat-select-country appearance="outline" country="IN" [itemsLoadSize]="5" (onCountrySelected)=&q ...

Create a Bootstrap grid that perfectly fits the viewport without any overflowing content

I'm currently utilizing Bootstrap 5 in an attempt to design a simplistic layout consisting of an MxN grid of cells, each of equal size. My goal is to have this grid fill the entire viewport without any scrollbars appearing in either direction. However ...

Is there a sophisticated method for breaking down a nested property or member from TypeScript imports?

Just curious if it's possible, not a big deal otherwise. import * as yargs from 'yargs'; // default import I'm looking to extract the port or argv property. This would simplify the code from: bootstrap(yargs.argv.port || 3000) to: ...

Pause code execution and prompt user interaction within a loop - React

I have been working on adding an "add all" button to my React app. To achieve this, I am passing a function to the onClick method of the button: for (element in elements) { await uploadfunction(element) } const uploadfunction = async (element) => ...

Implementing Dynamic Component Rendering in React Native with Typescript

For the past 3 hours, I've been grappling with this particular issue: const steps = [ { Component: ChooseGameMode, props: { initialValue: gameMode, onComplete: handleChooseGameModeComplete } }, { Com ...

Ways to implement logging in an NPM package without the need for a specific logging library

Currently, I am in the process of developing a company npm package using TypeScript and transferring existing code to it. Within the existing code, there are instances of console.log, console.warn, and console.error statements, as shown below: try { c ...

Following the Angular 6 update, a new error message "Error: Expected to find an ngsw-config.json configuration file" appears when running the ng build --prod command

After completing the update process, I encountered an issue during the build where the following error message appeared. Error: Expected to find an ngsw-config.json configuration file in the /Users/nathanielmay/Code/firebaseTest folder. Either provide ...

Ways to verify time synchronization in an Ionic 4 application to deter users from manipulating time to cheat or fake

In my Ionic 4 app built with Angular, I am utilizing Firebase through AngularFire to save and retrieve data. The main feature of my app is displaying a list of events from the database that occur within the next two days from the current time. Users also h ...

Angular's Reactive forms: The power of bidirectional binding

Struggling with Reactive forms? I've encountered an issue where updating the model class when a User changes the input is easy, but what about programmatically changing the model and reflecting those changes in the HTML form? In simplified terms: th ...

Verify the subscription status and return it within the canDeactivate function

When working with the CanDeactivate guard, I subscribe to a confirm service within which there are three buttons in the Confirm component. Each button triggers an enum value. How can I inspect this value within the subscription, perform certain actions bas ...