Skip to content

Instantly share code, notes, and snippets.

@ludndev
Created August 27, 2025 13:57
Show Gist options
  • Select an option

  • Save ludndev/1385f6ba3288a9b13f5f904e1c7c8505 to your computer and use it in GitHub Desktop.

Select an option

Save ludndev/1385f6ba3288a9b13f5f904e1c7c8505 to your computer and use it in GitHub Desktop.
Converts milliseconds to a concise, human-readable time format (e.g., "1h 30m")
function msToHumanReadable(ms: number): string {
const seconds = Math.floor(ms / 1000) % 60;
const minutes = Math.floor(ms / 60000) % 60;
const hours = Math.floor(ms / 3600000) % 24;
const days = Math.floor(ms / 86400000);
const parts: string[] = [];
if (days > 0) parts.push(`${days}d`);
if (hours > 0) parts.push(`${hours}h`);
if (minutes > 0) parts.push(`${minutes}m`);
if (seconds > 0 || parts.length === 0) parts.push(`${seconds}s`);
return parts.join(' ');
}
// --- Demo ---
const ms = 90 * 60 * 1000; // expecting "1h 30m"
const result = msToHumanReadable(ms);
console.log(`Millisecond ${ms} as human readable : ${result}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment