From b473ade1789ed5e84ea99caef05d94c9861d8620 Mon Sep 17 00:00:00 2001 From: ztimson Date: Fri, 25 Jul 2025 19:42:01 -0400 Subject: [PATCH] Added format milliseconds method --- package.json | 2 +- src/string.ts | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 6c6fb8b..2042c60 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@ztimson/utils", - "version": "0.26.16", + "version": "0.26.17", "description": "Utility library", "author": "Zak Timson", "license": "MIT", diff --git a/src/string.ts b/src/string.ts index d87f0b0..0179a50 100644 --- a/src/string.ts +++ b/src/string.ts @@ -43,6 +43,24 @@ export function formatBytes(bytes: number, decimals = 2) { return parseFloat((bytes / Math.pow(k, i)).toFixed(decimals)) + ' ' + sizes[i]; } +/** + * Convert milliseconds to human-readable duration + * @param {string} number milliseconds + * @return {string} formated duration + */ +export function formatMs(number: string): string { + const ms = parseInt(number, 10); + if (isNaN(ms) || ms < 0) return "Invalid input"; + const seconds = ms / 1000; + const minutes = seconds / 60; + const hours = minutes / 60; + const days = hours / 24; + if (days >= 1) return `${days.toFixed(1)} days`; + else if (hours >= 1) return `${hours.toFixed(1)} hours`; + else if (minutes >= 1) return `${minutes.toFixed(1)} minutes`; + else return `${seconds.toFixed(1)} seconds`; +} + /** * Extract numbers from a string & create a formated phone number: +1 (123) 456-7890 *