Files
ticcat/resources/js/utilities/customProperties.ts
2024-02-17 00:02:39 +01:00

72 lines
2.1 KiB
TypeScript

interface Number {
pad(n: number, char?: string): string,
durationify(): string
}
Number.prototype.pad = function(n, char = "0") {
return (new Array(n).join(char) + this).slice(-n)
}
Number.prototype.durationify = function () {
if (! this) {
return '0s'
}
const base = Number(this)
const days = Math.floor(base / 60 / 60 / 24)
const hours = Math.floor((base - (days * 60 * 60 * 24)) / 60 / 60)
const minutes = Math.floor((base - (days * 60 * 60 * 24) - (hours * 60 *60)) / 60)
const secondes = Math.floor(base - (days * 60 * 60 * 24) - (hours * 60 *60) - (minutes *60))
let duration = ''
duration += (days) ? `${days}j ` : ''
duration += (days > 0 || hours > 0) ? `${hours}h ` : ''
duration += (days > 0 || hours > 0 || minutes > 0) ? `${minutes}m ` : ''
duration += `${secondes}s`
return duration
}
interface Date {
toFrDate(): string,
toFrTime(): string,
toSmallFrDate(): string,
difference(start_at?: Date): string,
}
Date.prototype.toFrDate = function() {
return `${this.getDate()}/${Number(this.getMonth() + 1).pad(2)}/${this.getFullYear()}`
}
Date.prototype.toFrTime = function(separator = 'h') {
return `${this.getHours().pad(2, '0')}${separator}${Number(this.getMinutes()).pad(2)}`
}
Date.prototype.toSmallFrDate = function() {
if ((new Date(this)).toFrDate() === (new Date()).toFrDate()) {
return `${this.toFrTime()}`
}
if ((new Date(this)).getFullYear() === (new Date()).getFullYear()) {
return `${this.getDate()}/${Number(this.getMonth() + 1).pad(2)} ${this.toFrTime()}`
}
return `${this.toFrDate()} ${this.toFrTime()}`
}
Date.prototype.difference = function (start_at) {
if (!this) {
return '--:--'
}
let end_at = this
if (!start_at) {
end_at = new Date()
start_at = this
}
let timer = Math.floor((end_at.getTime() - start_at.getTime()) / 1000)
let hours = Math.floor(timer / 3600)
let minutes = Math.floor((timer - hours * 3600) / 60)
let secondes = timer - hours * 3600 - minutes * 60
return `${hours}:${String(minutes).padStart(2, '0')}:${String(secondes).padStart(2, '0')}`
}