I have a Date
prototype extension that I use in Angular project, defined as:
if (!Date.prototype.hasOwnProperty('toLocalISOString')) {
Date.prototype.toLocalISOString = function (): string | null {
try {
const date = new Date(this.valueOf());
const a = [
{ f: date.getFullYear(), pad: 4 },
{ f: date.getMonth() + 1, pad: 2 },
{ f: date.getDate(), pad: 2 },
{ f: date.getHours(), pad: 2 },
{ f: date.getMinutes(), pad: 2 },
{ f: date.getSeconds(), pad: 2 },
{ f: date.getMilliseconds(), pad: 3 }
];
const s = a.map(d => d.f.toString().padStart(d.pad, '0'));
return `${s[0]}-${s[1]}-${s[2]}T${s[3]}:${s[4]}:${s[5]}.${s[6]}`;
//return `${s[0]}-${s[1]}-${s[2]}T${s[3]}:${s[4]}:${s[5]}.${s[6]}Z`; //if using Z as identifier the time is considered UTC
}
catch {
return null;
}
}
The extension is declared in my global.d.ts
file as:
export { }
declare global {
interface Date {
toLocalISOString(): string | null;
}
}
With a function call in a component as below:
getAllSelect(startDate?: Date, endDate?: Date) {
let params = new HttpParams();
if (startDate && endDate)
{
const d1 = new Date(startDate).toLocalISOString() ?? '';
const d2 = new Date(endDate).toLocalISOString() ?? '';
}
'do stuff
}
if I use the function WITHOUT the new Date()
initializer, i.e.
const d1 = startDate.toLocalISOString() ?? '';
const d2 = endDate.toLocalISOString() ?? '';
I get an error message that toLocalISOString is not a function
even though startDate
& endDate
are both of type Date
?
if I include the new Date()
initializer it works as intended.
Would anyone be able to shed some more light on the intricate differences between the two methods and why the prototype extension doesn't get recognized from the Date | null
instance?