我搜索了其他问题,但找不到任何其他与此类似的问题。
我正在学习使用 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/