【问题标题】:How to convert Asp.Net Core DateTime to Angular Date using Constructor?如何使用构造函数将 Asp.Net Core DateTime 转换为 Angular Date?
【发布时间】:2019-12-14 06:36:16
【问题描述】:

我正在使用带有 Asp.Net Core 的 Angular 8。我目前遇到的问题是我无法使用 [(ngModel)] 和日期管道在模态中显示日期。

我想做的是在构造函数中将 Asp.Net Core DateTime 转换为 Angular Date 格式。

这是我的代码。 Created、StartDate 和 EndDate 都是 Date。

export class Content {
    Id: string;
    CompanyId: string;
    Created: Date; 
    Name: string;
    Url: string;
    Instructions: string;
    Tags: string; 
    StartDate: Date; 
    EndDate: Date;
    Deleted: Boolean;
    Pause: Boolean;
    Published: Boolean;

    constructor(contentResponse: any) {
        this.Id = contentResponse.id;
        this.CompanyId = contentResponse.companyId;
        this.Created = contentResponse.Created;
        this.Name = contentResponse.name;
        this.Url = contentResponse.url;
        this.Instructions = contentResponse.instructions;
        this.Tags = contentResponse.tags;
        this.StartDate = contentResponse.startDate;
        this.EndDate = contentResponse.endDate;
        this.Deleted = contentResponse.deleted;
        this.Pause = contentResponse.pause;
        this.Published = contentResponse.published;
    }

 }

从 console.log 中,我可以看到以下日期格式。

来自 API 的 JSON

创建:“2019-08-03T21:26:51.7981863”

结束日期:“2020-12-31T00:00:00”

开始日期:“2019-07-15T00:00:00”

使用当前构造函数转换后

已创建:未定义

结束日期:“2020-12-31T00:00:00”

开始日期:“2019-07-15T00:00:00”

有谁知道如何在构造函数中转换 this 以便 Angular 可以显示这些信息并使用它?

非常感谢任何帮助。谢谢!

【问题讨论】:

  • 在everyDate试试这个---> new Date("2019-08-03T21:26:51.7981863");
  • @sagat 谢谢!我在 EndDate 上尝试了这条确切的路线,看看会发生什么。这是结果。 EndDate: Sat Aug 03 2019 21:26:51 GMT-0500 (Central Daylight Time) {} 我看到一个 proto: 对象以及各种嵌套对象。此处不显示 [(ngModel)]="formModel.EndDate"。

标签: angular asp.net-core


【解决方案1】:

在您的 Angular 应用程序中尝试 Moment JS。我将它与许多带有 asp.net 和 asp.net 核心后端的 Angular 项目一起使用,完全没有问题。如果您想使用“本机”角度日期管道,您可以找到的唯一问题是本地化数据。但是您也可以将 moment 用于此类事情。

希望对你有所帮助。

【讨论】:

  • 谢谢!我在想这样的事情会起作用,但事实并非如此。 this.EndDate = new Date(moment(contentResponse.endDate).format('YYYY-MM-DD'));知道如何在我的特定情况下使用时刻吗?
  • 我建议使用 date fns,因为它比 moment 和 treeshakeable 轻得多 --> date-fns.org/v2.0.0-beta.4/docs/parse。对于您的问题,请查看此问题 --> stackoverflow.com/questions/22184747/…。简而言之,省略了新的 Date 语句,只有 moment(yourDateString).format(yourFormat)
  • 我不确定您为什么要设置 this.EndDate fo Date。为什么不直接使用 moment().format() 并准备好在视图上显示的字符串。如果你想存储在你的类中,你有两个选择:1-st 将 StartDate 和 EndDate 声明为 Moment 而不是 Date,或者 2-nd 保持原样,并且 convetr moment(contentResponse.endDate).toDate 没有“格式” - 你可以在视图中使用管道格式化日期或再次传递给 moment(EndDate).format('whatever-you-want')。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-23
  • 2011-11-21
相关资源
最近更新 更多