Skip to content

Instantly share code, notes, and snippets.

@weslleih
Last active November 11, 2023 08:00
Show Gist options
  • Star 33 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save weslleih/b6e7628416a052963349494747aed659 to your computer and use it in GitHub Desktop.
Save weslleih/b6e7628416a052963349494747aed659 to your computer and use it in GitHub Desktop.
Extend the TypeScript Date Object with some useful methods
export {}
declare global {
interface Date {
addDays(days: number, useThis?: boolean): Date;
isToday(): boolean;
clone(): Date;
isAnotherMonth(date: Date): boolean;
isWeekend(): boolean;
isSameDate(date: Date): boolean;
getStringDate(): String;
}
}
Date.prototype.addDays = function (days: number): Date {
if (!days) return this;
let date = this;
date.setDate(date.getDate() + days);
return date;
};
Date.prototype.isToday = function (): boolean{
let today = new Date();
return this.isSameDate(today);
};
Date.prototype.clone = function (): Date{
return new Date(+this);
};
Date.prototype.isAnotherMonth = function (date: Date): boolean {
return date && this.getMonth() !== date.getMonth();
};
Date.prototype.isWeekend = function (): boolean {
return this.getDay() === 0 || this.getDay() === 6;
};
Date.prototype.isSameDate = function (date: Date): boolean {
return date && this.getFullYear() === date.getFullYear() && this.getMonth() === date.getMonth() && this.getDate() === date.getDate();
};
Date.prototype.getStringDate = function (): String {
//Month names in Brazilian Portuguese
let monthNames = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
//Month names in English
//let monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
let today = new Date();
if (this.getMonth() == today.getMonth() && this.getDay() == today.getDay()) {
return "Hoje";
//return "Today";
} else if (this.getMonth() == today.getMonth() && this.getDay() == today.getDay() + 1) {
return "Amanhã";
//return "Tomorrow";
} else if (this.getMonth() == today.getMonth() && this.getDay() == today.getDay() - 1) {
return "Ontem";
//return "Yesterday";
} else {
return this.getDay() + ' de ' + this.monthNames[this.getMonth()] + ' de ' + this.getFullYear();
//return this.monthNames[this.getMonth()] + ' ' + this.getDay() + ', ' + this.getFullYear();
}
}
@kenrayspencer
Copy link

Perfect. Thanks

@robert35
Copy link

isSameDate does not take into account Offset and TimeZone, is your code of isSameDate valid when you compare let say 01/12/2023T23:30+01:00 (i don't know if this date can happen really) and 01/12/2023T00:20+00:00 ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment