Skip to content

Instantly share code, notes, and snippets.

Embed
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;
default:
return { d: days, h: hours, m: minutes, s: seconds };
}
};
@Dias999

This comment has been minimized.

Copy link

@Dias999 Dias999 commented Jan 10, 2019

This is awesome! Thank you!

@Captainfive

This comment has been minimized.

Copy link

@Captainfive Captainfive commented Jun 21, 2019

Thx dude, just one thing, breaking after a return isn't useful. the break is unreachable.

@flangofas

This comment has been minimized.

Copy link
Owner Author

@flangofas flangofas commented Jun 23, 2019

Thanks! Missed that ;)

@wkok

This comment has been minimized.

Copy link

@wkok wkok commented Jun 2, 2020

Thank you, wish I found your solution earlier, would've saved me 2 days.

@aaronangle

This comment has been minimized.

Copy link

@aaronangle aaronangle commented Sep 17, 2020

Thanks this works great!

@joaodjtr

This comment has been minimized.

Copy link

@joaodjtr joaodjtr commented Sep 18, 2020

Thanks 👏🏽!

@Nethanos

This comment has been minimized.

Copy link

@Nethanos Nethanos commented Nov 11, 2020

Thanks! This is awesome!

@petrone7

This comment has been minimized.

Copy link

@petrone7 petrone7 commented Dec 1, 2020

Thank you very much! works like a charm!

@godfern

This comment has been minimized.

Copy link

@godfern godfern commented Dec 9, 2020

Looks like the days giving a wrong value. The calculation for a day is giving an extra day.

Eg: if the difference between 2 dates i.e. from date: 02/12/2020 and to date: 09/12/2020 gives 8 days instead 7 days

@aznoisib

This comment has been minimized.

Copy link

@aznoisib aznoisib commented Feb 19, 2021

thx bro

@haydanu

This comment has been minimized.

Copy link

@haydanu haydanu commented Apr 19, 2021

nice

@maxmatyugin

This comment has been minimized.

Copy link

@maxmatyugin maxmatyugin commented Apr 24, 2021

thx! Very helpful!

@ARIPRASATH4664

This comment has been minimized.

Copy link

@ARIPRASATH4664 ARIPRASATH4664 commented May 5, 2021

Love

@DET171

This comment has been minimized.

Copy link

@DET171 DET171 commented Oct 20, 2021

+1

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