Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

send current date to Api using typescript in format (DateTime)

how can I send current date to API using typescript in a specific format (DateTime) when I send date to API, it's sent in this format so I got the error.

my ts code:

date: Date;
constructor( private dataStorageService: DataStorageService) {
    this.date = new Date();
}
onSubmit(Message , form : FormGroup){
    let newMsg = {
        username: Message.username,
        header: Message.header,
        content: Message.content,
        file: Message.file
    }
  this.dataStorageService.postMessage(newMsg, this.Id , this.date).subscribe(data => {
      console.log('done');
      console.log(this.date);
      }, error => {
          console.error("Error saving jobs!");
      })
}

http://api.azharcouncil.com/api/notification/PostNotification?user_id=15&Header=hj&Content=hjh&File_Path=null&date=Wed%20Nov%2015%202017%2010:44:56%20GMT+0200%20(Egypt%20Standard%20Time)

So my request is invalid because of the date format...

like image 939
Aya Abdelaziz Avatar asked Oct 27 '25 03:10

Aya Abdelaziz


1 Answers

Here is the complete answer to your question.

  1. Import the DatePipe from in the main module and provide that to your main module in main.module.ts in your provider array like given below:

    import {DatePipe} from '@angular/common';    
    providers: [DatePipe]
    
  2. Use it in your ts file with these methods, also import DatePipe from @angular/common in your ts file as well.

    import {DatePipe} from '@angular/common';
    
  3. Then in your constructor initialize this:

    constructor(private _http: HttpClient, public datepipe: DatePipe) { }
    
  4. Now use these methods to get the correct date format:

    let myDate = new Date(); 
    console.log(this.datepipe.transform(myDate, 'yyyy-mm-dd'));
    someDateVar = this.datepipe.transform(myDate, 'yyyy-mm-dd');
    
  5. Now someDateVar can be used to send it to server which has the date format you need. Also note that you can use multiple other date formats as well which are given in the Angular date pipe documentation.

like image 114
Deepak Jha Avatar answered Oct 28 '25 17:10

Deepak Jha