The method getDay is not recognized as a function in Typescript Angular

After searching for a solution, I came across a similar question that did not address the specific issue I am dealing with.

The challenge I am facing involves parsing a date into a string. Below is my current implementation:

export class DataFormater {

    formatDDMMMYYY(date: Date): string {
        return date.getDay().toString() + '/' + date.getMonth().toString() + '/' + date.getFullYear().toString();
    }

}

However, an error occurs stating that date.getDay() is not a function. Upon reviewing the documentation, I discovered that it is returning a number, hence the need to use .toString(). Has anyone encountered this issue before or come up with a better way to parse a date into a desired output string?

-------------- Full Implementation ----------

<input class="form-control" placeholder="yyyy-mm-dd"
                           name="dp" ngbDatepicker #d="ngbDatepicker" [(ngModel)]="fromDate" (keyup)="setFilter()">

In Component

toDate: Date;
fromDate: Date;

constructor(private dateFormatter: DataFormater) {
    this.toDate = new Date();
    this.fromDate = new Date();
}

setFilter() {    
        if (this.toDate != null) {
            console.log(this.toDate + " in toDate...");
            this.filter.toDate = this.dateFormatter.formatDDMMMYYY(this.toDate);
        }
        if (this.fromDate != null) {
            this.filter.fromDate = this.dateFormatter.formatDDMMMYYY(this.fromDate);
        }
        this.filterEmitter.emit(this.filter);
    }

DataFormater Class

export class DataFormater {

    constructor(){
        console.log(this.formatDDMMMYYY(new Date))
    }

    formatDDMMMYYY(date: Date): string {
        date = new Date(date);
        return date.getDay().toString() + '/' + date.getMonth().toString() + '/' + date.getFullYear().toString();
    }

}

Answer №1

It seems that the date format being passed to the function is incorrect.

You can try the following approach:

constructor(){
  console.log(this.formatDate(new Date))
}

formatDate(date: Date): string {
   return date.getDate().toString() + '/' + (date.getMonth()+1).toString() + '/' + date.getFullYear().toString();
}

View Working Demo

Note: If you need to convert the id to DD/MM/YYYY, use date.getDate() instead of date.getDay(). Using date.getDay() will give you the day of the week, starting from Sunday as 0. For example, Friday would be represented as 5.

Answer №2

It is possible that the getDate() function is being called on an invalid date object, resulting in an error.

To resolve this issue, make sure to provide a valid date object when using the function. For example:

this.formatDDMMMYYY(new Date());

Here is an updated solution based on the question:

Try changing this part to new Date(this.fromDate)

this.filter.fromDate = this.dateFormater.formatDDMMMYYY(new Date(this.fromDate));

setFilter() {    
        if (this.toDate != null) {
            console.log(this.toDate + " in toDate...");
            this.filter.toDate = this.dateFormater.formatDDMMMYYY(this.toDate);
        }
        if (this.fromDate != null) {
            this.filter.fromDate = this.dateFormater.formatDDMMMYYY(new Date(this.fromDate));
        }
        this.filterEmitter.emit(this.filter);
    }

DateFormater

export class DataFormater {

    constructor(){
        console.log(this.formatDDMMMYYY(new Date))
    }

    formatDDMMMYYY(date: Date): string {
        return date.getDate().toString() + '/' + date.getMonth().toString() + '/' + date.getFullYear().toString();
    }

}

Answer №3

When working with the ngbDatepicker, I encountered a situation where it was not using native TypeScript dates. To resolve this issue, I implemented the following solution:

import {NgbDate} from '@ng-bootstrap/ng-bootstrap';

toDate: NgbDate;
fromDate: NgbDate;

To parse the date properly, I added the following code snippet:

    if (this.fromDate != null) {
        this.filter.fromDate = this.dateFormater.formatDDMMMYYY(this.fromDate);
    }

Next, I created a method for formatting the date:

import {NgbDate} from '@ng-bootstrap/ng-bootstrap';

export class DataFormater {

    formatDDMMMYYY(date: NgbDate): string {
        return date.day + '/' + date.month + '/' + date.year;
    }

}

Answer №4

Don't bother with converting strings, just pass the date directly to the function:

Give this a go:

 constructor() {
    console.log(this.formatDDMMMYYY(new Date()));
  }

  formatDDMMMYYY(date: Date): string {
    return moment().format("DD/MM/YYYY");
  }

Check out the live demonstration

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 happens when a typed Array in Typescript has an undefined property?

I've encountered an issue with a seemingly simple problem that's causing me quite the headache. The code snippet in question is provided below: interface IFoo{ ReturnFirstBarObject1(): string; FillBarArray(array: Array<Bar>): void; } ...

The Next.js website displays a favicon in Chrome, but it does not appear in Brave browser

As I work on my debut next.js website, I am configuring the favicon in index.js like this: <Head> <title>Create Next App</title> <link rel="icon" href="/favicon.ico" /> </Head> Initially, all my source ...

Exploring the functionality of Angular's Material Virtual Scroll and incorporating the scrollToIndex method

Is there a way to manage the scrollToIndex (virtual scroll) if my list is not loaded during the ngAfterViewInit lifecycle? I need to trigger the scroll to a specific index when redirecting from another page, which happens in the ts file. My objective is to ...

The compilation of TypeScript and ES Modules is not supported in Firebase Functions

Recently, I integrated Firebase Functions into my project with the default settings, except for changing the value "main": "src/index.ts" in the package.json file because the default path was incorrect. Here is the code that was working: // index.ts cons ...

Remove focus from input field after submitting in a project using Typescript and React with react-hook-form

I'm currently working on a TS-React project and encountering an issue with barcode scanning in my inputs. I am using react-hook-form along with the useForm Hook. The form consists of one input-text field and a submit button, both within a global form. ...

Tips for keeping a specific key value pair as the final entry in a Typescript Object

My goal is to construct a Typescript Object that has a specific element with the key 'NONE' always positioned at the end. This arrangement is crucial for displaying the object in my HTML page with this value appearing last. I am seeking an implem ...

Is there a way to verify the selected navigation item in the console?

Need help with checking the selected navigation using console.log? export const navItems: NavData[] = [ { name: 'Book #1', url: '/book', icon: 'fa fa-book', children: [{ name: 'Book #2', ...

What is the best way to include a Generic type into a functional component's props that also extends a different interface for its props?

Explanation I am currently working on developing a dynamic input form using the FormProvider feature from react-hook-form. const formMethods = useForm<TSongFormData>(); return ( <FormProvider {...formMethods}> <SongInputForm /> ...

Typescript: Defining the correct return type for resolved parameters in promises

Exploring the world of TypeScript, I recently attempted to convert some basic JavaScript promise samples into TypeScript promises. While working on this conversion process, I encountered an issue that has left me puzzled and unable to find a solution even ...

Removing the final element within a nested array: a step-by-step guide

let originalArray=[ [ "Test1", "4", "160496" ], [ "Test2", "6", "38355" ], [ "Test3", "1", "1221781" ], [ " ...

Leverage the retrieved configuration within the forRoot function

Currently working on an Angular app that uses @ngx-translate. In my implementation, I am using TranslateModule.forRoot(...) to set up a TranslateLoader: @NgModule({ imports: [ TranslateModule.forRoot({ loader: { provide: TranslateLoade ...

Tips for effectively changing Observable data into an Array

I am currently attempting to transform an Observable into an Array in order to loop through the Array in HTML using ngFor. The Typescript code I have now is causing some issues. When I check the testArray Array in the console, it shows up as undefined. it ...

The button click function is failing to trigger in Angular

Within my .html file, the following code is present: The button labeled Data Import is displayed.... <button mat-menu-item (click)="download()"> <mat-icon>cloud_download</mat-icon> <span>Data Imp ...

Properties undefined

All of my functions are giving errors indicating that the props are not defined. The error specifically relates to the word "props" in the following functions: function PostButton(props) function PostButton2(props) function TotalVotes(props) ...

Exploring Array Iteration with RxJS' Filter and Map Functions

Can someone help me figure out the correct way to iterate over an array using map and filter in my Angular project? Currently, both methods expect a single value, but I am dealing with an Observable that contains an array. Any guidance on how to do this co ...

Navigating through async functions in an Express.js router

Encountered a lint error indicating that Promises cannot be returned in places where a void is expected. Both functions [validateJWT, getUser] are async functions. Any suggestions on how to resolve this issue without compromising the linter guidelines by u ...

What is the best way to reduce the viewport size of my application to 67% of the Chrome browser view?

Recently, I acquired an Angular application that comes with hundreds of SCSS files. However, when the application is viewed in a browser set to 100%, it appears ugly and too zoomed in. Applying zoom: 70%; to the index.html body improves the appearance, bu ...

The Angular directive ng-if does not function properly when trying to evaluate if array[0] is equal to the string value 'Value'

In my code, I want to ensure that the icon is only visible if the value at array index 0 is equal to 'Value': HTML <ion-icon *ngIf="allFamily[0] === 'Value'" class="checkas" name="checkmark"></ion-icon> TS allFamily = [ ...

Unable to swap out string with text box in TypeScript

I am trying to swap __ with a text box in Angular 2/4. Take a look at the example provided in the link below. https://stackblitz.com/edit/angular-ajkvyq?file=app%2Fapp.component.ts ...

Encountering an issue while attempting to start ng serve due to the error message stating "Module '@angular/compiler-cli' cannot be located"

I am facing an issue with running my Angular project. Whenever I try to execute ng serve, it fails with the following error: dev@716a5115c45c:~/project$ npx ng serve Cannot find module '@angular/compiler-cli' Error: Cannot find module '@ang ...