简体   繁体   中英

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#.

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

An alternate solution to using DatePipe would be the use of formatDate . I have passed the following values: date, time format, and locale as its parameters.

On your component.ts, you can do something like this:

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

export class AppComponent  {
  locale: string = 'en-US';
  format: string = 'dd-mm-yyyy'
  date: Date = new Date();

  constructor() {}

  transformDate(date) {
    console.log(formatDate(this.date, this.format, this.locale));
    return formatDate(this.date, this.format, this.locale);
  }
}

I have reproduced a demo to demonstrate the usage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM