Last active
April 22, 2022 05:09
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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