Skip to content

Instantly share code, notes, and snippets.

@nilsandrey
Last active April 22, 2022 05:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nilsandrey/08e748d6ca02e30d8dbe23d5e3d24f92 to your computer and use it in GitHub Desktop.
Save nilsandrey/08e748d6ca02e30d8dbe23d5e3d24f92 to your computer and use it in GitHub Desktop.
Extensions to the TypeScript Date class to work with diferences to a future date.
export {};
/**
* Extensions to the Typescript Date class.
*/
declare global {
/**
* Extension members declarations.
*/
interface Date {
/**
* Returns time left from today to the date in milliseconds.
*/
timeLeft(): number;
/**
* Check if current date already past the date or there are less than 24 hours left to it.
*/
isLastDay(): boolean;
/**
* Returns the hours left to the date as extracted from
* sentence like "There are hh:mm:ss left to the date".
*/
hoursLeft(): number;
/**
* Returns the minutes left to the date as extracted from
* sentence like "There are hh:mm:ss left to the date".
* (NOT the total minutes)
* To be used as a complement to `hoursLeft()`.
*/
minutesLeft(): number;
/**
* Returns the seconds left to the date as extracted from
* sentence like "There are hh:mm:ss left to the date".
* (NOT the total seconds)
* To be used as a complement to `minutesLeft()`.
*/
secondsLeft(): number;
}
}
Date.prototype.timeLeft = function (): number {
return this.getTime() - new Date().getTime();
};
Date.prototype.isLastDay = function (): boolean {
return this.timeLeft < 86400000;
};
Date.prototype.hoursLeft = function (): number {
return Math.floor(this.timeLeft() / 3600000);
};
Date.prototype.minutesLeft = function (): number {
return Math.floor((this.timeLeft() % 3600000) / 60000);
};
Date.prototype.secondsLeft = function (): number {
return Math.floor((this.timeLeft() % 60000) / 1000);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment