Skip to content

Instantly share code, notes, and snippets.

Last active August 22, 2023 18:42
  • Star 42 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
JS: Convert Milliseconds to days? minutes? seconds? or all!
function convertMiliseconds(miliseconds, format) {
var days, hours, minutes, seconds, total_hours, total_minutes, total_seconds;
total_seconds = parseInt(Math.floor(miliseconds / 1000));
total_minutes = parseInt(Math.floor(total_seconds / 60));
total_hours = parseInt(Math.floor(total_minutes / 60));
days = parseInt(Math.floor(total_hours / 24));
seconds = parseInt(total_seconds % 60);
minutes = parseInt(total_minutes % 60);
hours = parseInt(total_hours % 24);
switch(format) {
case 's':
return total_seconds;
case 'm':
return total_minutes;
case 'h':
return total_hours;
case 'd':
return days;
return { d: days, h: hours, m: minutes, s: seconds };
Copy link

haydanu commented Apr 19, 2021


Copy link

thx! Very helpful!

Copy link


Copy link

DET171 commented Oct 20, 2021


Copy link

You are a STAR!

Copy link

Beautiful! Thanks

Copy link

medamin25 commented Aug 30, 2022

simple real time calculator for this

Copy link

nforne commented Feb 8, 2023

Good job!
Principle : "Fail fast and early if you have to and recover soonest"
So I'll suggest you return zero on the third line if the milliseconds argument is zero, or any out of order input.
Some sort of error handling I suppose.
It saves on infrastructure cost and improves app performance when the other lines of code don't have to pointlessly run .
Like so .......

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment