Converting a date input to string(Angular)

Viewed 37

I have this project but I am hitting an issue.

I want to convert my date input to the following "1990-01-01T05:00:00.000+00:00" format.

I tried using toISOString() but I still can't create a new movie because of the date I'm guessing. Below is my code.

export class CreateMovieComponent implements OnInit {
 public title = '';
 public date = new Date().toISOString();
 constructor(public http: HttpClient) {}

ngOnInit(): void {}

 createMovie() {
 console.log('The title is ' + this.title + ' and the date of ' + this.date);
 this.http
  .post('http://localhost:8081/actors', {
    title: this.title,
    releaseDate: this.date,
  })
  .subscribe((data) => {
    console.log('data: ' + data);
  });
 }
}
1 Answers

You can use datePipe to format dates, to inject the pipe in your component you need to declare it in the provider module:

@NgModule({
  providers: [DatePipe]
})

Then you can declare the Date pipe in the component's constructor and used:

export class AppComponent {
  date = new Date();

  constructor(private datePipe: DatePipe) {}

  get dateString(): string {
    return this.datePipe.transform(this.date, 'yyyy-mm-ddThh:mm:ss.SSSZZZZZ');
  }
}

For example you can look at here: https://stackblitz.com/edit/angular-ivy-gpdrmu

Related