With the in-build Date type, I can call date.getDate(), date.getMonth()...etc. However, I want to create a way to call
date.myCustomFunctionToGetMonthInString(date) which returns month in string format such as 'Jan', 'Feb'... etc. Is there a way to build such extension?
At the moment I have created a CustomDate class but it seems overkill.
export class CustomDate {
day: number;
month: number;
year: number;
customDateString: string;
constructor(date: Date) {
this.day = date.getDate();
this.month = date.getMonth();
this.year = date.getFullYear();
var month_str: string;
switch (date.getMonth()) {
case 0:
month_str = 'Jan';
break;
case 1:
month_str = 'Feb';
break;
case 2:
month_str = 'Mar';
break;
case 3:
month_str = 'Apr';
break;
case 4:
month_str = 'May';
break;
case 5:
month_str = 'Jun';
break;
case 6:
month_str = 'Jul';
break;
case 7:
month_str = 'Aug';
break;
case 8:
month_str = 'Sep';
break;
case 9:
month_str = 'Oct';
break;
case 10:
month_str = 'Nov';
break;
case 11:
month_str = 'Dec';
break;
default:
month_str = 'Some Error';
}
this.customDateString = date.getDate().toString() + ' ' + month_str + ' ' + date.getFullYear().toString();
}
I have a read only input field. When the user clicks on the input, a calendar appears where the selection gets populated in the input field. Hence, I dont have direct access to the "picked date" from the HTML. So I am not sure how I can implement pipe here (I'd also like to know how to create extensions even if Pipe is the way to go).
This the HTML code of interest.
<label>Start Time</label>
<input (focus)="toggleTimePicker(true)" readonly class="form-control" formControlName="startTime" />
<time-picker *ngIf="showTimePicker" [showSecond]="false" (onTimePickerCancel)="toggleTimePicker($event)" (onSelectTime)="setTime($event)"></time-picker>
The read only input triggers a function to activate a time picker. After the user selects from the picker, setTime($event) is fired. And when that is fired, the read-only input field is populated with the date and time using the following method
this.myForm.controls['startTime'].setValue(dateTime)
Hence, I dont have access to the date in my HTML code since I am not using ngModel (My form is Reactive so I am avoiding to use ngModel)
<label>Start Time</label>
<input (focus)="toggleTimePicker(true)" readonly class="form-control" formControlName="startTime" />
<time-picker *ngIf="showTimePicker" [showSecond]="false" (onTimePickerCancel)="toggleTimePicker($event)" (onSelectTime)="setTime($event)"></time-picker>
setTime(dateTime: Date): void {
console.log(dateTime.getHours());
console.log(dateTime.getMinutes());
this.myForm.controls['startTime'].setValue(dateTime);
}
switch... casefor month conversion. Just create a simple array of months['Jan', 'Feb', 'Mar'...]and use indices to extract the proper month, i.e.months[date.getMonth()].