Reducing the date by one day using Angular 9

ngOnInit(): void {
    this.currentDate = new Date();
    this.date = this.datePipe.transform(this.currentDate, 'y-MM-dd');
    this.currentDate = this.date;
}

The code snippet above is used to retrieve the current date. The task at hand involves subtracting a day from this current date in order to obtain yesterday's date.

Answer №1

To display yesterday's date, utilize the code snippet below.

export class DateComponent implements OnInit{
    datePipe = new DatePipe('en');
    public today?: Date;
    public yesterday?: string | null;

  ngOnInit(){
    // Testing the 'getYesterday()' method.
    console.log(this.getYesterday());
  }

  getYesterday(){
    this.today = new Date();
    this.today.setDate(this.today.getDate() - 1);
    // Return the formatted date.
    return this.yesterday = this.datePipe.transform(this.today, 'dd-MM-y');
  }
}

Answer №2

This method increases or decreases the date by a specified number of days in the passed Date object. If a negative value is passed, it will subtract the days instead.

function adjustDateByDays(date: Date, daysToAdd: number): Date {
        date.setDate(date.getDate() + daysToAdd);
        return date;
    }

    console.log(adjustDateByDays(new Date(), -1));

Also, it is recommended to avoid using pipes in your components and check out How to format a JavaScript date for detailed information on formatting dates.

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

The date selected in matDatepicker does not match the formControl in Angular 8 when using Reactive Forms

https://i.stack.imgur.com/aHSyM.pngI am facing an issue with matDatepicker in Angular. The date retrieved from the API to populate my formControl using Reactive Forms is not matching the value displayed in matDatepicker. While the matDatePicker shows "12/3 ...

Developing a dynamic object in Typescript to structure and optimize API responses

Currently Working Explanation: This is similar to the data array received from the API response responseBarDataStacked = [ { sku: "Data 1", month: "Jun", value: 20 }, { sku: "Data 2", month: "Jun", value: 25 ...

Error message: Unable to retrieve parameter value from Angular2 ActivatedRoute

I am attempting to showcase the value of the activated route parameter on the screen, but I am facing difficulties. In the initial component, my code looks like this: <ul *ngFor="let cate of categories;"> <li (click)="onviewChecklists(cate.id) ...

Utilizing TypeScript 2's Absolute Module Paths

The issue at hand: I am facing a challenge with relative module paths and have attempted to resolve it by configuring the baseUrl setting in my tsconfig.json file. Despite my efforts, I keep receiving an error indicating that the module cannot be found. I ...

Unable to retrieve information from service using Angular 1.6 and TypeScript

I'm having an issue retrieving data from a Service in my Controller. Here is the code for my Service file: import {IHttpService} from 'Angular'; export class MyService { public static $inject = ['$http']; constructor(private $htt ...

Version 4.0 of Electron-React-Boilerplate has encountered an error: The property 'electron' is not recognized on the type 'Window & typeof globalThis'. Perhaps you meant to use 'Electron' instead?

I encountered an error while attempting to call the IPCrenderer using the built-in context bridge. The error message reads as follows: Property 'electron' does not exist on type 'Window & typeof globalThis'. Did you mean 'Elect ...

What kind of type is recommended to use when working with async dispatch in coding?

For my TypeScript and React project, I am currently working on an action file called loginAction.tsx. In this file, there is a specific line of code that handles the login functionality: export const login = (obj) => async dispatch => { dispatch( ...

Angular client created by NSwag uploads a file to a .NET Core backend

I'm facing a challenge with uploading a file to my controller using .NET Core 6.0 backend and an Angular client generated by NSwag. My controller has a model that contains an 'IFormFile' called file. [HttpPost("single-file"), DisableReques ...

Table arranged by column orientation

I am facing a unique scenario where the backend data I receive is organized in a column-oriented format. Here is an example of how the data structure looks: [ { columnName: "ID", cells: [1, 2, 3, 4, 5] }, { columnName: "Name", cells: ["a", "b", "c ...

Angular 4 - capturing and resending HTTP requests post-login

My HttpInterceptor is designed to monitor specific JWT token events (token_expired, token_not_provided and token_invalid) that can occur at various stages within the workflow. These events may be triggered when a user switches routes OR when an AJAX reque ...

Angular: The property '**' is not found on the type 'Object'

Not too long ago, I embarked on a new Angular project where my setup involves Angular (the front-end) communicating with a node.js server (the back-end), which in turn might make requests to an api server or a mongo database when necessary. The tricky par ...

Tips for postponing input validation in Angular 2+

When working with AngularJS, it is possible to use a directive to delay validation on an input field by setting the appropriate options. link(scope, elem, attr, ngModel) { ngModel.$overrideModelOptions({ updateOn: 'default blur', ...

Tips on ensuring that only one Angular Material expansion panel expands at a time

I have designed a mat expansion panel and I would like to ensure that only one panel can be expanded at a time. In other words, I want it so that when one record is expanded and I click on another record of the mat expansion, the previously expanded reco ...

Challenges with implementing Typescript in Next.js and the getStaticProps function

Having trouble with the implementation of getStaticProps where the result can be null or some data. The typings in getStaticProps are causing issues, even after trying conditional props. Any suggestions? type ProductType = { props: | { ...

Running Protractor e2e tests with various Angular environment variables is a great way to test your application in

I utilize Angular environment variables to easily set up API endpoints. You can find these configurations in the following environment files: .\src\environments: environment.ts environment.test.ts environment.prod.ts These environme ...

How can I target and focus on a dynamically generated form in Angular 4/Ionic3?

One of the challenges I'm facing is dealing with dynamically created forms on a page. Each row consists of inputs and a button. Is there a way to select/focus on the input by clicking on the entire row (button)? It should be noted that the number of r ...

Accessing external data in Angular outside of a subscription method for an observable

I am struggling to access data outside of my method using .subscribe This is the Service code that is functioning correctly: getSessionTracker(): Observable<ISessionTracker[]> { return this.http.get(this._url) .map((res: Response) => ...

Filter error - Unable to retrieve property 'toLowerCase' from null value

When filtering the input against the cached query result, I convert both the user input value and database values to lowercase for comparison. result = this.cachedResults.filter(f => f.prj.toLowerCase().indexOf((this.sV).toLowerCase()) !== -1); This ...

An issue with the validation service has been identified, specifically concerning the default value of null in

Using Angular 10 and Password Validator Service static password(control: AbstractControl) { // {6,100} - Check if password is between 6 and 100 characters // (?=.*[0-9]) - Ensure at least one number is present in the strin ...

Can you explain the step-by-step process of how an await/async program runs in TypeScript/JavaScript or Python?

As a C++ developer specializing in multithreading, I've been diving into the intricacies of async/await. It's been a challenge for me as these concepts differ from how C++ programs are typically executed. I grasp the concept of Promise objects, ...