Skip to content

Instantly share code, notes, and snippets.

@madcampos
Forked from weslleih/date.extensions.ts
Last active September 5, 2022 21:17
Show Gist options
  • Save madcampos/dca5a56163c4fe605b2e5fad2f093559 to your computer and use it in GitHub Desktop.
Save madcampos/dca5a56163c4fe605b2e5fad2f093559 to your computer and use it in GitHub Desktop.
Extend the TypeScript Date Object with some useful methods
/**
* Fork of: https://gist.github.com/weslleih/b6e7628416a052963349494747aed659
* Important notice: when using with node you need the package `full icu` installed and configured or compile node with full-icu support.
* This way the compiled js code can run using language data other then `en-us`.
*/
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;
}
}
//TODO: collect language data.
let translatedTerms = new Map([
['en-us', {'today': 'Today', 'tomorrow': 'Tommorow', 'yesterday': 'Yesterday', 'conective': 'of'}],
['pt-br', {'today': 'Hoje', 'tomorrow': 'Amanhã', 'yesterday': 'Ontem', 'conective': 'de'}]
]);
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 (locale = 'en-us', overrides = {}): String {
let terms = Object.assign(translatedTerms.get(locale) || {}, translatedTerms.get('en-us'), overrides);
let today = new Date();
let monthName = new Intl.DateTimeFormat(locale, {'month': 'long'}).format(this);
if (this.getMonth() == today.getMonth() && this.getDay() == today.getDay()) {
return terms.today;
} else if (this.getMonth() == today.getMonth() && this.getDay() == today.getDay() + 1) {
return terms.tomorrow;
} else if (this.getMonth() == today.getMonth() && this.getDay() == today.getDay() - 1) {
return terms.yesterday;
} else {
return `${this.getDay()} ${terms.conective} ${monthName} ${terms.conective} ${this.getFullYear()}`;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment