Search code examples
c#angularangular6

How to pass only date from angular 6 to web api


I am passing date from my angular 6 application to web api. The problem is when I select for example 10th March 2019 from datepicker. When I get that in web api it's converting it into 9th March 6:30 pm, I think its some with the time zone, but I dont need time I just want to pass date.

Following is angular code

  getBookingList() {

    this.bookingListSubscription = this.restService.getBookingListForGrid(this.booking).subscribe(
  data => {
    setTimeout(() => {
      if (data.status = '200') { 
      this.bookingList = data;
      this.bookingList.forEach((element) => {
        element.StartDate =  this.datePipe.transform(element.StartDate, "dd/MM/yyyy"),
          element.EndDate = new Date(element.EndDate);
      });
    }, 3000)
  });
  }

And I am storing date into DateTime format in c#.


Solution

  • You can use angular's DatePipe:

    Import this:

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

    and in constructor:

    constructor(private datePipe: DatePipe){}
    

    and to change the format of selected date you can simply use transform method:

    this.datePipe.transform(this.date, "your_expected_date_format"); // Format: dd/MM/yyyy OR dd-MM-yyyy OR yyyy-MM-dd
    

    TS Code:

    import {Component} from '@angular/core';
    import {FormControl} from '@angular/forms';
    
    
    import { DatePipe } from '@angular/common';
    
    /** @title Select with multiple selection */
    @Component({
      selector: 'select-multiple-example',
      templateUrl: 'select-multiple-example.html',
      styleUrls: ['select-multiple-example.css'],
       providers: [
        DatePipe
      ]
    })
    export class SelectMultipleExample {
    
      date : any;
      formatedDate : any;
    
      constructor(private datePipe: DatePipe){}
    
      onSubmit(){
       this.formatedDate =  this.datePipe.transform(this.date, "dd/MM/yyyy");
      }
    }
    

    Stackblitz