【问题标题】:Formatting Date Time toDateString in Typescript在打字稿中将日期时间格式化为日期字符串
【发布时间】:2019-10-23 12:18:44
【问题描述】:

我搜索了其他问题,但找不到与此类似的其他问题。

我正在学习使用 typescript 中的接口和类。我正在使用 toDateString 方法,就日期字符串格式而言,我得到了正确的输出,但我没有得到我在类实例化中定义为参数的正确日期。经过头脑风暴和偏头痛,我想我解决了这个问题,但我不确定这是否是正确的方法,或者是否有更好的方法。

这是我的接口,它定义了 currentDate 对象和 printDate 方法,并且类型为 void。

interface appointment{
currentDate:Date;
printDate():void;

}

然后是实现约会接口的类AppointmentDateFormatter。在构造函数中,我将数字类型定义为年、月和日

class AppointmentDateFormatter implements appointment{
currentDate:Date;

constructor(year:number, month:number, day:number){
    this.currentDate = new Date(year, month, day );

现在,我使用类型为 void: 的 printDate() 方法将使用 toDateString() 方法格式化的日期记录到控制台。

}
printDate():void {
    console.log(this.currentDate.toDateString());
}

在类实例化中我设置了我想登录到控制台的日期参数。

const AppointmentDate = new AppointmentDateFormatter(2019, 10 , 28);

AppointmentDate.printDate();

但是我得到了错误的日期---> 2019 年 11 月 28 日星期四,而不是 10 月,这是它应该登录到控制台的月份。因为我注意到它提前了一个月,所以我决定在数字 10 上加上一个负 1,我认为这是有道理的,因为 10 实际上是数字类型,因此我会得到实际的月份 10现在是十月,令人惊讶的是它奏效了!

const AppointmentDate = new AppointmentDateFormatter(2019, 10 - 1 , 28);

我只是想知道这种方法是否正确,以及是否有其他我可以做的事情被认为是实现预期结果的更合适的方法。我真的很感激你的回答。

这是包含 (2019, 10 - 1, 28) 审核的完整代码。

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>


interface appointment{
    currentDate:Date;
    printDate():void;

}

class AppointmentDateFormatter implements appointment{
    currentDate:Date;

    constructor(year:number, month:number, day:number){
        this.currentDate = new Date(year, month, day);
        

}
    printDate():void {
        console.log(this.currentDate.toDateString());
    }
}

const AppointmentDate = new AppointmentDateFormatter(2019, 10 - 1 , 28);

AppointmentDate.printDate();

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    在 typescript 或 javascript 中,日期月份以 (0 到 11) 开头。 因此,当您通过 new Date(2019,10,28) 时意味着这是 11 月。

    因此,您必须以 new Date() 应该为您提供正确日期的方式编写逻辑..

    我会建议您使用 .ToDateString(),而不是使用 angular datePipe。

    this.datepipe.transform(new Date(2019,10,28) , 'yyyy-MM-dd') // syntax for datepipe
    

    确保您是否在 Angular 类构造函数中注入了日期管道。

    完整示例

    export class AppComponent {
    
      constructor(
        private datePipe: DatePipe,
      )
      convertDateToFormat() {
        const dateIs = this.datePipe.transform(new Date(2019, 10, 28), 'yyyyMMdd');
      }
    }
    

    注意: import { DatePipe } from '@angular/common';

    【讨论】:

    • 您介意举个例子说明我需要如何使用 datePipe 吗?谢谢你。是否需要安装任何特定的软件包才能使用角度 datePipe?
    • 我的答案已经修改,请查收。
    • 这是内置的角度包,所以不需要安装任何额外的东西。
    猜你喜欢
    • 2020-08-07
    • 2012-09-07
    • 1970-01-01
    • 2016-10-21
    • 2023-03-14
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    相关资源
    最近更新 更多