【发布时间】: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