javascript - 在 Typescript 中将日期时间格式化为 DateString

标签 javascript typescript

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

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

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

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

}

然后是实现约会接口(interface)的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();

最佳答案

在 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 类构造函数中注入(inject)了 datepipe。

完整示例

export class AppComponent {

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

注意:从'@angular/common'导入{DatePipe};

关于javascript - 在 Typescript 中将日期时间格式化为 DateString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58515073/

相关文章:

javascript - 如何在点击时使用 jQuery 动态加载 WordPress 自定义帖子类型数据?

Angular 单元测试 : Using Generics to Create Component

匿名自执行函数的 typescript 范围问题

typescript - 如何避免函数在 TypeScript 的子类中被覆盖?

typescript - 通用类型错误 TS2322 : Type '{ id: null; }' is not assignable to type 'T'

javascript不区分大小写仅匹配字符串的一部分

javascript - 如何通过JQuery获取HTML表格单元格值?

javascript - DataTables - 使用单个下拉列表在多列中搜索

reactjs - 如何在带有 typescript 的 React 中正确使用 useState 钩子(Hook)?

javascript - 如何使用 javascript 创建弹出页面