Struggling to extract the hours and minutes from a date in IONIC: encountering an error stating that getHours is not a recognized

I encountered an issue while trying to extract the hours and minutes from a date in Ionic.

Below is the code snippet from my .html file :

  <ion-datetime displayFormat="HH:mm" [(ngModel)]='timeEntered1' picker-format="h:mm"></ion-datetime>
  <ion-button (click)="getTime()"></ion-button>

Next, in my .ts file, I implemented the following logic:

timeEntered1 = new Date();

constructor() {}

getTime() {
  console.log(this.timeEntered1.getHours());
}

The error message displayed is as follows:

this.timeEntered1.getHours is not a function

Answer №1

In order to achieve this, make sure to incorporate the <button> element into your code.

 <ion-datetime displayFormat="HH:mm" [(ngModel)]='timeEntered1' picker-format="h:mm"></ion-datetime>
    <button ion-button (click)="getTime()"></button>

For a demonstration, check out this link: https://stackblitz.com/edit/ionic-jkhwaw

Answer №2

When you select a time like 2:03 in this scenario, Ionic provides the following output:

{
    "hour": {
        "text": "2",
        "value": 2,
        "columnIndex": 0
    },
    "minute": {
        "text": "03",
        "value": 3,
        "columnIndex": 1
    }
}

This means that you no longer need to use getHours() since the values are already stored in your model. You can simply do the following:

timeEntered1 = <any>{};

getTime() {
  // This will display 2 and 3
  console.log(this.timeEntered1.hour.value, this.timeEntered1.minute.value);
}

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

In Angular/Typescript, dynamically add a class to a `td` element when it is clicked. Toggle the class on and off

My problem arises when trying to individually control the arrow icons for each column in my COVID-19 data table. By using Angular methods, I aim to show ascending and descending arrows upon sorting but run into the challenge of changing arrows across all c ...

Refill ag-grid with fresh data

Setting up the ag-grid initialization directly from the HTML using an onGridReady method in the component file. <div style="flex-grow:1;"> <ag-grid-angular style="float:left;width: 100%; height: 201px;margin-top:10px;" class="ag- ...

What is the best way to define a named, optional parameter in TypeScript-React that can accept an object with optional fields and default values?

Is there a way to achieve something similar to the style property found in default HTML components? For instance: <div ref={ref} style={{ overflow: 'visible', height: 600, width: '100%' }}> The style prop is optional, and the fie ...

Tips for customizing Material UI CSS default properties in React

I'm currently working on a React project and utilizing the 'Table' component from Material UI. The default CSS properties of this table, along with its components like TableHead, TableCell, and TableRow, are proving difficult to override whi ...

Can a constructor function be utilized as a parameter type in another function within TypeScript?

Recently, I came across TypeScript and after watching some video reviews, I see great potential in it. It seems to offer better code completion, implicit code documentation, and enhanced type safety for JavaScript. I'm currently in the process of con ...

Changing a string to HTML within an Angular 2 application

Is there a simple way to convert a string to HTML? I am attempting to convert a string containing valid HTML, href links, and line breaks. Currently, I am utilizing the DOMParser().parseFromString method as outlined on https://developer.mozilla.org/en-US ...

Include a hash in the URL when the current location is entered into the view by scrolling

In my current situation, I am required to implement a @HostListener in order to navigate to an element within my web page: @HostListener('click', ['$event']) onClick(e: any) { e.preventDefault(); const href = e.target.getAttri ...

Transferring AgGrid context in a functional React component

I have been working on a component that utilizes AgGrid to display a table, with the data sourced from a Redux selector. My goal is to include a button within a cell in the table that triggers an action based on the specific row's data. However, I a ...

When trying to run "ng s -o/ng s/ng build" commands in Angular Cli, there is an issue where no output is displayed

Running "ng serve", "ng serve -o", and "ng build" does not display any output. I am in need of Angular for my project, so if anyone can offer assistance, please help me. https://i.sstatic.net/SmjaL.jpg ...

Is it possible to insert a button into a specific column of an ngx-datatable within an Angular 8 application?

I am having trouble with this particular HTML code. <ngx-datatable-column name="Option" prop="option" [draggable]="false" [resizeable]="false [width]="250"> <span> <button class="optionButton" type="button" data-to ...

Creating a dynamic text design using Bootstrap or CSS: What's the best approach?

I attempted to enable responsive font sizes in Bootstrap 4.3.1 by setting the $enable-responsive-font-sizes variable to true, but I did not see any changes. Below is the code from my template.html file: <div class="m-2" id="role" ...

A comprehensive guide to using Reactive Forms in Angular

I need help understanding how FormGroup, FormControl, FormArray work in Angular. The error message I'm encountering is: Type '{ question: FormControl; multi: true; choices: FormArray; }' is not assignable to type 'AbstractControl' ...

What other options exist besides RxJS operators?

Imagine a scenario like this: submit(): void { this.loading = true; dataLength?: number = untracked(this.dataService.data)?.length; this.dataService.addData(this.dataForm.value); effect( () => { if (this.dataLength !== thi ...

Tips for utilizing and incorporating an icon into a specific cell within ag-grid to signify that the cell can be edited

I am currently integrating ag-grid with angular 6. There is a specific column that needs to have editable cells. You can refer to the image below for better clarity. Is there a way to include an icon that, once clicked, allows the cell to become editable? ...

The specified file cannot be found within the Node file system

I am working on a project that involves reading a file using Node fs, and I have the following code: const files: FileSystemTree = { "Component.tsx": { file: { contents: fs.readFileSync( `../../apps/components ...

Declarations for TypeScript in NPM packages

In order to streamline my development process with bun.sh using workspaces as npm packages, I have created a tool available here. However, I am facing two issues: After bun installing the 'core' packages from npm and testing a sample, I encounte ...

determine the values of objects based on their corresponding keys

Still on the hunt for a solution to this, but haven't found an exact match yet. I've been grappling with the following code snippet: interface RowData { firstName: string; lastName: string; age: number; participate: boolean; } c ...

An error has occurred: Type 'x' is not compatible with type 'x' (during Vercel deployment)

I encountered an issue during Vercel deployment which displays the following error message: - Type error: Type ' ({ params }: DashboardPageProps) = Promise' is not compatible with type 'FC<.DashboardPageProps>' Type 'Promise ...

How can I rectify the issue in TypeScript where the error "not all code paths return a value" occurs?

While developing an application, I encountered an error that says: "not all code paths return a value". The error is specifically in the function named addValues, indicating that the function must return "Obj[] | undefined". Here is the code snippet in qu ...

The Angular application integrated with Keycloak experiences an endless loading loop when the page is refreshed or after the user logs in

One approach I've been trying to maintain the current state of my Angular app (the URL) when refreshing the page is by modifying the redirectUri in the isAccessAllowed function: public async isAccessAllowed( route: ActivatedRouteSnapshot, ...