【问题标题】:How to pass only date from angular 6 to web api如何仅将日期从角度 6 传递到 web api
【发布时间】:2019-08-14 03:11:58
【问题描述】:

我将日期从我的 Angular 6 应用程序传递到 Web api。问题是当我从 datepicker 中选择例如 2019 年 3 月 10 日时。当我在 web api 中得到它时,它会将其转换为 3 月 9 日下午 6:30,我认为它与时区有关,但我不需要时间,我只想通过日期。

下面是角码

  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)
  });
  }

我在 c# 中将日期存储为 DateTime 格式。

【问题讨论】:

  • WebAPI 端的预期格式是什么?即yyyy-MM-dd?
  • 如果我选择 10/03/2019,我只需要日期示例,那么它应该通过接收相同的。在 dd-mm-yyyy
  • 在这种情况下您需要处理时区。如果您在后端执行 new Date(yourDate) ,它将根据服务器时区转换日期。请提供一些后端代码!
  • 没有时间...?
  • 是的,没有时间

标签: c# angular angular6


【解决方案1】:

你可以使用angular的DatePipe:

导入这个:

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

在构造函数中:

constructor(private datePipe: DatePipe){}

要更改所选日期的格式,您可以简单地使用转换方法:

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

TS 代码:

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

【讨论】:

  • 收到错误类型“字符串”不可分配给类型“日期”
  • element.StartDate = this.datePipe.transform(element.StartDate, "dd/MM/yyyy"),
  • 我希望它是 Date 类型而不是字符串,它可以传递给 web api 并且可以存储在 c# 的 DateTime 类型中
  • 把它改成any C# 会接受这个
  • 将其更改为在 c# 中签入的任何仍然获得相同结果日期 - c# 中的 5:30 小时
【解决方案2】:

使用DatePipe 的另一种解决方案是使用formatDate。我传递了以下值:日期、时间格式和语言环境作为其参数。

在您的 component.ts 上,您可以执行以下操作:

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);
  }
}

我转载了一个demo来演示用法。

【讨论】:

  • 获取错误类型“字符串”不可分配给类型“日期”
  • 等等,什么?哦,你从哪里得到这个错误?你的意见是什么?
猜你喜欢
  • 1970-01-01
  • 2015-11-20
  • 2017-12-01
  • 1970-01-01
  • 2020-01-26
  • 1970-01-01
  • 2019-07-02
  • 1970-01-01
  • 2023-04-05
相关资源
最近更新 更多