Last active
October 25, 2022 21:44
-
-
Save t1mofe1/42cd340340914fd2c57e7c962436e95c to your computer and use it in GitHub Desktop.
IMPORTANT!! `formatStrToTime` will show different result if you did `formatTimeToStr` with different depth
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 const timeUnits = [ | |
// { name: "y", milliseconds: 31_536_000_000 }, | |
// { name: "mo", milliseconds: 2_592_000_000 }, | |
{ name: "d", milliseconds: 86_400_000 }, | |
{ name: "h", milliseconds: 3_600_000 }, | |
{ name: "m", milliseconds: 60_000 }, | |
{ name: "s", milliseconds: 1_000 }, | |
{ name: "ms", milliseconds: 1 }, | |
]; | |
/** | |
* @function formatTime | |
* @param {number} time - unix timestamp | |
* @param {number} depth - how many time units to show (default: 2) | |
* @returns {string} formatted total time. Example: 15d 5h 25m 4s | |
*/ | |
export function formatTimeToStr(time: number, depth = Infinity) { | |
const formattedTime: string[] = []; | |
let remainingTime = time; | |
// TODO: calculate years and months by starting from the current date or provided date in param | |
for (const timeUnit of timeUnits) { | |
const timeUnitValue = Math.floor(remainingTime / timeUnit.milliseconds); | |
if (timeUnitValue > 0) { | |
formattedTime.push(`${timeUnitValue}${timeUnit.name}`); | |
remainingTime -= timeUnitValue * timeUnit.milliseconds; | |
} | |
} | |
return formattedTime.slice(0, depth).join(" "); | |
} | |
/** | |
* @function formatTime | |
* @param {string} str - string with all time formats joined with space. Example: "5h 21m 37s" | |
* @returns {number} total time in milliseconds | |
*/ | |
export function formatStrToTime(str: string) { | |
const timeArr = str.split(" "); | |
let time = 0; | |
// TODO: calculate years and months by starting from the current date or provided date in param | |
for (const timeUnit of timeUnits) { | |
const timeUnitValue = timeArr.find((timeStr) => | |
timeStr.endsWith(timeUnit.name) | |
); | |
if (timeUnitValue) { | |
time += | |
Number(timeUnitValue.slice(0, -timeUnit.name.length)) * | |
timeUnit.milliseconds; | |
} | |
} | |
return time; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment