【问题标题】:How to resolve "Date" is not instanceof Date issue?如何解决“日期”不是实例日期问题?
【发布时间】:2019-07-17 20:53:53
【问题描述】:

在对我的 ngx-bootstrap-bsDatepicker 控件和 FormGroup 中的“无效日期”进行故障排除时,我发现了我正在使用的对象 (this.ts.startDateTime) 上的日期值问题。与new Date() 对象相比。

08:11:03.723 ts-form.component.ts:240 HZyWZhwowB - this.ts.startDateTime 2019-07-16T20:18:24.9133333
08:11:03.724 ts-form.component.ts:242 HZyWZhwowB - testDate Wed Jul 17 2019 08:11:03 GMT-0400 (Eastern Daylight Time)
08:11:03.724 ts-form.component.ts:244 HZyWZhwowB - this.ts.startDateTime instanceof Date false
08:11:03.725 ts-form.component.ts:246 HZyWZhwowB - testDate instanceof Date true

有问题的属性是:

/**
  * Gets or sets the start date.
  */
startDateTime: Date;

很容易看出这些值是不同的。我的对象是从 HTTP 请求接收到 WebAPI 控制器的数据,并且 typescript 接口是从 WebAPI 中的模型生成的。对于大多数应用程序,对象的 Date 值在其当前状态下工作。

在 Angular 应用程序中解决此问题并将此值转换为实际日期的最佳方法是什么?

Angular 5 - ASP.NET API
momentjs 存在于应用程序中,但当前未在我的组件中使用。

【问题讨论】:

  • 显然,您的 ts.startDateTime 是 ISO 字符串格式。您可以通过将 Date 对象传递给 Date() 构造函数来创建一个 Date 对象:Date(this.ts.startDateTime)

标签: angular typescript date ngx-bootstrap


【解决方案1】:

ts.startDateTime 是一个字符串,所以你必须转换为一个 Date 对象:

let myDate = new Date(this.ts.startDateTime);

请记住遵守您的标准 (ISO 8601),以避免破坏上述代码。

【讨论】:

  • 我最终在 Angular 应用程序中找到了一个 DateService,它本质上就是这样做的(尽管 startDateTime 是一个带有字符串值的日期)。所以是let stringDate = new String(date); 然后是let validDate = new Date(stringDate.toString());
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-11
  • 1970-01-01
相关资源
最近更新 更多