Vishal
Vishal

Reputation: 139

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

Upvotes: 3

Views: 13979

Answers (3)

Ramesh Bolla
Ramesh Bolla

Reputation: 412

I had the same issue, spent lot of time to fix.Instead of sending as datetime type, I sent to backend as a string. Since its Rest API endpoint, automatically converted to Date Time.

model.dateOfBirth = new Date(moment(model.dateOfBirth).format('MM/DD/YYYY')).toDateString();

This solved my problem.

Upvotes: 0

wentjun
wentjun

Reputation: 42516

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.

Upvotes: 0

Prashant Pimpale
Prashant Pimpale

Reputation: 10697

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

Upvotes: 4

Related Questions