Change the ddmmyy date string to dd/mm/yyyy format using TypeScript

When I use the date picker onchange method, the date is passed as a string like ddmmyyyy (20102020) to dd/mm/yyyy. I am unsure of how to convert the date format from ddmmyyyy to dd/mm/yyyy. In the CustomDateParserFormatter, the string needs to be converted from ddmmyyyy to dd/mm/yyyy.

@Injectable()
export class CustomDateParserFormatter {
    parse(value: string): NgbDateStruct {
        if (!value) {
            return null;
        }
        const parts = value;
        parts.split('/');
        console.log("first calling");
        return { year: +parts[0], month: +parts[1], day: +parts[2] } as NgbDateStruct;

    }
    format(date: NgbDateStruct): string {
        // tslint:disable-next-line:prefer-template
        console.log("second calling");
        return date ? ('0' + date.day).slice(-2) + '/' + ('0' + date.month).slice(-2) + '/' + date.year : null;
    }
}

    <input class="form-control"
           placeholder="DD/MM/YYYY"
           ngbDatepicker
           formControlName="dateofBrith"
           [minDate]="{year: 1975, month: 1, day: 1}"
           [maxDate]="{year: 2020, month: 12, day: 31}"
           name="dp"
           #d="ngbDatepicker"
           (ngModelChange)="changeDob($event)"
           maxlength="10">
        <div class="input-group-append">
            <button class="btn calendar btn-custom btn-outline-secondary"
                    (click)="d.toggle()"
                    type="button"><img src="/assets/images/dateicon.png"></button>
        </div>

    changeDob(value) {}

When using this method, I receive the value from the date picker onclick as {year:2020,month:10,day:10}. However, when the user manually enters the date in the input field instead of clicking, the value is received as a string. I am struggling with converting the format and need guidance on how to proceed. Your understanding is greatly appreciated.

Answer №1

Looking for the solution to changing the date format in NgbDatePicker from JSON to yyyy-mm-dd? You can find the answer in the 3rd response on this page. I used the yyyy-mm-dd format, but you have the option to switch to dd-mm-yyyy in your typescript code. Simply adjust the final line to

let finalDate = day + "/"+ month + "/" + year ;

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

Running Swagger within an Angular 5 environment - a step-by-step guide!

How do I integrate Swagger into my UI? Here's what I tried: import * as SwaggerUI from 'swagger-ui'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.c ...

I am looking to extract only the alphanumeric string that represents the Id from a MongoDB query

Working with mongoDB, mongoose, and typescript, I am facing an issue where I need to preserve the document ids when querying. However, all I can retrieve is the type _id: new ObjectId("62aa4bddae588fb13e8df552"). What I really require is just the string ...

Encountering an undefined value in Angular outside of the subscription

I am facing an issue where I need to use the value from the user outside the subscribe function in order to assign it to my tweet class. However, when I try to print it outside the subscribe function, it shows as undefined. Can anyone provide a solution fo ...

Tips for Receiving Error Messages with Patterns in Angular 2

After several attempts, I am unable to get this code to function correctly. <div> <span *ngIf="!usernameRef.errors?.required">Amount</span> <span *ngIf="!usernameRef.errors?.required">Cover amount is necessary.</span& ...

Mastering error handling in Angular's Http requests

In my frontend application using Angular, I need to communicate with a RESTful webservice for the login process. The webservice returns different response codes in JSON format depending on the success or failure of the login attempt: If the login is corre ...

What could be the reason for passport.serializeUser function not being available?

After spending nearly an hour searching, I am still unable to pinpoint the issue in my code. Not only have I failed to find a solution online, but reaching out for help in coding communities on Discord has also been futile as no one seems to know why this ...

Choosing options using an enum in Angular 2

In my TypeScript code, I have defined an enum called CountryCodeEnum which contains the values for France and Belgium. export enum CountryCodeEnum { France = 1, Belgium = 2 } Now, I need to create a dropdown menu in my form using this enum. Each ...

Error in Angular Template Parsing Due to Dynamic Object Key in Angular Version Greater Than 2

When I attempt to assign a value for a key with a variable inside my event binding expression, an unexpected error occurs: Parser Error: Unexpected token [, expected identifier, keyword, or string at column... the expression in question is: (ngModelChange ...

Is there a specific instance where it would be more appropriate to utilize the styled API for styling as opposed to the sx prop in Material-

I am currently in the process of migrating an existing codebase to Material UI and am working towards establishing a styling standard for our components moving forward. In a previous project, all components were styled using the sx prop without encounteri ...

The functionality of the Auth0 Logout feature has ceased to work properly following the

Previously, the code worked flawlessly on Angular version 14. However, after updating to version 17 due to persistent dependency issues, a problem arose. logout(): void { sessionStorage.clear(); this.auth.logout({ returnTo: window.location.origin } ...

Using React and TypeScript to Consume Context with Higher Order Components (HOC)

Trying to incorporate the example Consuming Context with a HOC from React's documentation (React 16.3) into TypeScript (2.8) has been quite challenging for me. Here is the snippet of code provided in the React manual: const ThemeContext = React.creat ...

Having trouble with the environment.ts file during Angular 2 testing

Having issues while attempting to write a basic test in Angular 2, specifically with an error related to environment.ts: ERROR in ./web/environments/environment.ts Module build failed: Error: web\environments\environment.ts is missing from ...

What is the process for incorporating a Static Class into a Declaration File in TypeScript?

I'm in the process of developing a UMD library using TypeScript. The first class I have created is a static one with a method. The name of my Library is SuperLib and here is the code snippet: export class Security { static userExists ( user: string ...

Tips for linking an Express JS server to an Angular 6 file?

I have been researching how to create a user login system using Express, Node.js, and Angular. However, I haven't found a clear answer on how to add new pages with Angular. Can someone guide me on the process and recommend the necessary modules to use ...

Twilio CORS Angular HttpClient Integration

Currently attempting a "GET" request to the Twilio API using HttpClient module import { HttpClient } from '@angular/common/http'; Utilizing Angular CLI: 6.0.8 Node: 8.11.3 OS: darwin x64 Testing in both Firefox and Chrome, but running into th ...

Can the rxjs take operator be utilized to restrict the number of observables yielded by a service?

As someone who is just starting to learn Angular, I am working on a website that needs to display a limited list of 4 cars on the homepage. To achieve this, I have created a service that fetches all the cars from the server. import { Response } from &apos ...

The problem with uploading files in Angular4 (with multer on the server)

In my current project, I encountered an issue where the front end file was not getting transferred to the server side after finishing both the front end and back end logic. Despite spending more than an hour debugging, I couldn't pinpoint the exact ca ...

Displaying the initial element in an NgFor loop in Angular 2

Whenever I click on the "Add row" button, I dynamically generate a row of inputs and dropdowns. Upon clicking another button, the complete data is submitted and displayed in console.log as an array of objects, with each object representing a single row. C ...

Identify modifications in NGRX state before shutting down

In my Angular application, I am utilizing NGRX to manage state. Users are able to switch between different versions of the store, each saved and reloaded from a database. It's important for me to detect when changes have been made to the store but not ...

How can I remove a row from a mat table using Angular?

Having trouble implementing *ngFor in my angular mat table, seeking guidance from someone with more expertise? I am trying to delete a row within an array using a button and display it on my table, but encountering issues. I intend to utilize *ngFor to sh ...