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

Creating TypeScript unit tests for nested functions: A step-by-step guide

I'm currently working with Angular 16 in combination with the ngRx framework. My development involves TypeScript coding and writing unit tests (.spec.ts) using Jasmine, especially for code similar to the example below. How do I invoke this method with ...

Retrieve information from matSnackBar using openFromComponent

Hello there! As a newcomer to Angular, I am interested in retrieving data from matsnackbar. Is this something that can be achieved? apiName: string; this.snackBar.openFromComponent(CustomSnackbarComponent, { duration: 5000000, dat ...

`Is there a way to display a server-side file (image) in Angular using rendering techniques?`

After successfully saving a file in the database using my Java server, I am now faced with the challenge of displaying that file on my Angular side. The file is of MIME type image/jpg. When attempting to send a GET request, I can retrieve the image correc ...

Tips for using an ArrayBuffer to stream media in Angular

Currently, I am facing an issue while transferring data from my backend with nodeJS to Angular. Everything seems to be working fine except for one problem - my media files are not functioning properly in my code. To resolve this, I have implemented Blob fi ...

Peer dependencies in NPM refer to dependencies that your project

I am currently in the process of upgrading from Angular 4 to Angular 5 and encountered some warnings along the way. Some of the warnings I received include: npm WARN @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88eb ...

What is the process for incorporating buttons into an Angular mat-table?

I have successfully utilized Angular mat-table to showcase data retrieved from a database: view the image description here <table mat-table [dataSource]="UserDataSourceFilters" class="mat-elevation-z1 mt-5"> <ng-co ...

Why does WebStorm fail to recognize bigint type when using TSC 3.4.x?

Currently, I am working on the models section of my application and considering switching from using number to bigint for id types. However, despite knowing that this is supported from TSC 3.2.x, WebStorm is indicating an error with Unresolved type bigint. ...

What is the solution for fixing an error that says "There is no 'style' property on the 'Element' type"?

I'm struggling to fix an error in my JavaScript code. I created a script to display a tab indicator when a tab is clicked, but I keep getting the error message: "Property 'style' doesn't exist on type 'Element'". The tabs them ...

Creating a Loading Sign with a Button Component in React

Request Description: In my form, I have a button that triggers a submission to the backend. While the request is processing, I want the button to display a loading indicator instead of the usual text. Once the request is complete, I need the form to disap ...

The lib.dom.d.ts file is seriously lacking in many key components

Are there any updated versions of lib.dom.d.ts? The current one is missing a lot of essential information, causing numerous compilation errors. For example, consider this line: window.File && window.FileReader && window.FileList && ...

Retrieve the component when there is a change in the variable in Angular versions greater than 4

When invoking the ngx-ebar-treemo component in my main component, I use the following syntax: <ngx-ebar-treemo *ngIf="type=='Bar' && graphic" type1="{{type1}}" type2="{{type2}}"></ngx-ebar-treemo> I need to call this compone ...

Unable to bind service data to the kendoUI grid

I'm in the process of developing an angular 4 component incorporating kendoUI. While using the kendoUI grid to display json data, I've encountered a debugging issue. The service seems to be retrieving records successfully, but for some reason, th ...

When utilizing the package, an error occurs stating that Chart__default.default is not a constructor in chart.js

I have been working on a project that involves creating a package with a react chart component using chart.js. Everything runs smoothly when I debug the package in storybook. However, I encountered an error when bundling the package with rollup, referenc ...

React 18 update causes malfunctioning of react-switch-selector component

I'm facing an issue where the component is not rendering. I attempted to start a new project but it still didn't work. Is there a solution to fix this problem or should I just wait for an update from the original repository? Encountered Error: ...

I'm looking for a way to implement a jQuery-style initialization pattern using TypeScript - how can I

My library utilizes a jQuery-like initialization pattern, along with some specific requirements for the types it should accept and return: function JQueryInitializer ( selector /*: string | INSTANCE_OF_JQUERY*/ ) { if ( selector.__jquery ) return select ...

Execution issue with Typescript function

In my Nativescript project, I have the following TypeScript file: import { Observable } from 'tns-core-modules/data/observable'; import { isIOS } from "tns-core-modules/platform"; import { Color } from "tns-core-modules/color"; import { request, ...

Retrieve the input type corresponding to the name and return it as a string using string template literals

type ExtractKeyType<T extends string, K extends number> = `${T}.${K}`; type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends readonly unknown[] ? ExtractKeyType<Key, 0 | 1> : T[Key] extends Record<str ...

Issue with ngb-carousel not properly loading upon page refresh within an Angular project

I have integrated ngb-carousel into my Angular application for a basic website. Overall, everything is functioning correctly, but I have noticed that when I refresh the page, the carousel's image takes longer to load compared to the indicators and arr ...

Issue encountered while setting up controls and AbstractControls in form development

Here is a snippet of code showing how I create and manipulate a form in Angular: this.myForm = new FormGroup({ points: new FormArray([ new FormGroup({ date: this.date, startTime: new FormControl(null, Val ...

The exclude option in Nest JS middleware does not prevent the middleware from running on excluded routes

I'm having an issue with excluding certain routes from the middleware. The .exclude option doesn't seem to be working as expected, as the middleware is still being applied to the excluded routes. Here is the code for the Middleware: https://i.st ...