How Can I format Date in typescript?

You can use Angular's DatePipe. In the component where you want to format:

add

providers: [DatePipe]

then import class

import { DatePipe } from '@angular/common';

then inject in constructor

constructor(public datepipe: DatePipe){}

and then in the code you can format like

this.datepipe.transform(this.dueDate, 'yyyy/MM/dd')

change format from 'yyyy/MM/dd' to any you need


Edit:

if you do not want to use any library then you can use builtin angular's DatePipe

Follow the step to use datePipe:

1: Import DatePipe:

import { DatePipe } from '@angular/common';

2: Add **DatePipe in your module's providers:**

NgModule({
      providers: [DatePipe]
    })
    export class AppModule {
    }

Or you can add datePipe into your component's providers:

@Component({
      selector: 'target-selector',
      styleUrls: ['./target.component.css'],
      templateUrl: './target.component.html',
      providers: [DatePipe]
    })
    export class TargetComponent {
    ...

3: Now inject it into constructor:

constructor(private datePipe: DatePipe) {
}

4: Ready to use:

this.datepipe.transform(this.myDate, 'yyyy/MM/dd');

Or

 this.datepipe.transform(this.myDate, 'MM/dd/yyyy');

You can use

new Date().toLocaleString() => "11/10/2016, 11:49:36 AM"

then use string.slice to get the part opf the string you want


Property 'datepipe' does not exist on type 'HomeComponent'. Did you mean 'datePipe'?ts(2551)

i am getting aboue issue ,datePipe without declared