I searched through other questions, but couldn't find any other problem like this one.
I am learning to work with interfaces and classes in typescript. I am using the toDateString method, and I am getting the right output as far as the date string format, but I am not getting the right date that I have defined as parameters in the class instantiation. After brain storming and getting a migraine, I think I fixed the problem, but I'm not sure if it was the right approach, or if there is a better way.
This is my interface which it has the currentDate object and a printDate method defined and with a type of void.
interface appointment{
currentDate:Date;
printDate():void;
}
Then the class AppointmentDateFormatter which implements appointment interface. In the constructor I have defined number types to the year, month and day
class AppointmentDateFormatter implements appointment{
currentDate:Date;
constructor(year:number, month:number, day:number){
this.currentDate = new Date(year, month, day );
Now here, I use the printDate() method with the type of void: to log to the console the date formatted using the toDateString() method.
}
printDate():void {
console.log(this.currentDate.toDateString());
}
In the class instantiation I set the parameters of the date I want to log to the console.
const AppointmentDate = new AppointmentDateFormatter(2019, 10 , 28);
AppointmentDate.printDate();
But I get the wrong date back---> Thu Nov 28 2019 instead of Oct which it's the month it should've logged to the console. Since I noticed that it was giving me a month ahead, I decided to put a minus 1 to the number 10 and I thought it would make sense since the 10 is actually of type number, I would get as a result the actual month 10 which it's October and surprisingly it worked!
const AppointmentDate = new AppointmentDateFormatter(2019, 10 - 1 , 28);
I'd just like to know if this approach is the right one, and if there was something else I could've done that would be considered a more proper way of accomplishing the expected result. I'd truly appreciate your answers.
This is the entire code with the (2019, 10 - 1, 28) moderation included.
<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();