Converting milliseconds to minutes and seconds with Javascript
I’ve tried many functions I found on here to no avail. I’m just looking for something to convert that number to something like looks like this:
Here’s one that got close, but doesn’t work. It doesn’t stop the seconds at 60. It goes all the way to 99 which makes no sense. Try entering «187810» as a value of ms, for example.
var ms = 298999, min = Math.floor((ms/1000/60)
What do you mean, "it goes all the way to 99"? Your script is working for me, properly outputting 4:58 . Please provide an input that leads to the unexpected output.
187810 is an example of it not working. It's goes all the way to 99. There are not 99 seconds in a minute.
15 Answers 15
function millisToMinutesAndSeconds(millis) < var minutes = Math.floor(millis / 60000); var seconds = ((millis % 60000) / 1000).toFixed(0); return minutes + ":" + (seconds < 10 ? '0' : '') + seconds; >millisToMinutesAndSeconds(298999); // "4:59" millisToMinutesAndSeconds(60999); // "1:01"
As User HelpingHand pointed in the comments the return statement should be:
return ( seconds == 60 ? (minutes+1) + ":00" : minutes + ":" + (seconds < 10 ? "0" : "") + seconds );
Let it be known that this solution sometimes results in sixty seconds in the second place when nearing conversion to the next minute (ex. 1:60 ). I stop this from happening by adding an inline if statement in the last line: return (seconds == 60 ? (minutes+1) + ":00" : minutes + ":" + (seconds < 10 ? "0" : "") + seconds); You can see it in action here
That's a good point by HelpingHand - you can reproduce the issue by running millisToMinutesAndSeconds(299900)
@maerics Shouldn't ((millis % 60000) / 1000).toFixed(0) be Math.floor((millis % 60000) / 1000) so seconds is a number instead of a string when it is being compared to another number.
return should be return minutes + ":" + seconds.ToString("00"), where seconds should be (Math.Round(millis % 60000 / 1000, 0, MidpointRounding.ToEven);
Proposal of renaming for this function: formatToISODuration . don't bother with the millisecond in the name, the parameter does the job. And always write user-PoV names, no inner technical details. Plus "And" in a function name is always a bad idea.
I'm not really sure why these answers are all so complex. The Date class gives you what you need:
const date = new Date(298999); alert(`$:$`);
Although the above meets op's requirements, adding this updated version in response to @ianstarz comment regarding timezone independence:
const d = new Date(Date.UTC(0,0,0,0,0,0,298999)), // Pull out parts of interest parts = [ d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds() ], // Zero-pad formatted = parts.map(s => String(s).padStart(2,'0')).join(':'); document.write(formatted);
Looks like OP is indeed only asking for seconds and minutes. This solution would not work for hours and days however. date.getHours() // => 16 (in my timezone)
@Madbreaks you might want to do it for your first example too, otherwise the simplicity is misleading
This should be the accepted answer as it is simpler, less error prone than other solutions and uses the language's built-in resources
With hours, 0-padding minutes and seconds:
var ms = 298999; var d = new Date(1000*Math.round(ms/1000)); // round to nearest second function pad(i) < return ('0'+i).slice(-2); >var str = d.getUTCHours() + ':' + pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds()); console.log(str); // 0:04:59
In some use cases it might be better to drop the second (2nd) row (rounding to the nearest second). For example, if we want to know the full seconds left, this would return "4:58".
@Madbreaks if you're suggesting pad is reinventing the wheel, note the answer is from 2014 yet your use of padStart is part of EMCAScript 2017.
@Matt my bad. I deleted my previous comment. I do suggest using native JS classes/functions however when possible.
Here's my contribution if looking for
function msConversion(millis) < let sec = Math.floor(millis / 1000); let hrs = Math.floor(sec / 3600); sec -= hrs * 3600; let min = Math.floor(sec / 60); sec -= min * 60; sec = '' + sec; sec = ('00' + sec).substring(sec.length); if (hrs >0) < min = '' + min; min = ('00' + min).substring(min.length); return hrs + ":" + min + ":" + sec; >else < return min + ":" + sec; >>
function msToTime(duration) < var milliseconds = parseInt((duration%1000)) , seconds = parseInt((duration/1000)%60) , minutes = parseInt((duration/(1000*60))%60) , hours = parseInt((duration/(1000*60*60))%24); hours = (hours
It will return 00:04:21.223 You can format this string then as you wish.
No need to reinvent the wheel. Look at the Date class and the methods it offers you. The "best" is always to use native solutions.
@Madbreaks I'm not sure how you would do pure formatting like this with date since you would have to deal with timezones. Can you provide and example of what you mean?
There is probably a better way to do this, but it gets the job done:
var ms = 298999; var min = ms / 1000 / 60; var r = min % 1; var sec = Math.floor(r * 60); if (sec < 10) < sec = '0'+sec; >min = Math.floor(min); console.log(min+':'+sec);
Getting the remainder of the minutes with % gives you the percentage of seconds elapsed in that minute, so multiplying it by 60 gives you the amount of seconds and flooring it makes it more fit for display although you could also get sub-second precision if you want.
If seconds are less than 10 you want to display them with a leading zero.
Event though ,oment.js does not provide such functionality, if you come here and you are already using moment.js, try this:
function formatDuration(ms)
You will get something like x:xx:xx.
In the case you may want to skip the hour, when the duration is only < 60minutes.
function formatDuration(ms) < var duration = moment.duration(ms); if (duration.asHours() >1) < return Math.floor(duration.asHours()) + moment.utc(duration.asMilliseconds()).format(":mm:ss"); >else < return moment.utc(duration.asMilliseconds()).format("mm:ss"); >>
This workaround in moment was introduced in this Issue.
If you do not need support for hours, there's a clever little way of doing this with momentjs and dayjs.
A millisecond timestamp passed to MomentJS and DayJS will be interpreted as the number of milliseconds since the Unix Epoch, therefore any time duration not affected by timezone (ie any number of milliseconds less than one hour) will be interpreted correctly.
// ✅ You can use a Quick one-liner hack const ms = 54000000; console.log(new `enter code here`Date(ms).toISOString().slice(11, 19)); // 👉️ 15:00:00 // ------------------------------------------------ // ✅ Or create a reusable function function padTo2Digits(num) < return num.toString().padStart(2, '0'); >function convertMsToTime(milliseconds) < let seconds = Math.floor(milliseconds / 1000); let minutes = Math.floor(seconds / 60); let hours = Math.floor(minutes / 60); seconds = seconds % 60; minutes = minutes % 60; // 👇️ If you don't want to roll hours over, e.g. 24 to 00 // 👇️ comment (or remove) the line below // commenting next line gets you `24:00:00` instead of `00:00:00` // or `36:15:31` instead of `12:15:31`, etc. hours = hours % 24; return `$:$:$`; > console.log(convertMsToTime(54000000)); // 👉️ 15:00:00 (15 hours) console.log(convertMsToTime(86400000)); // 👉️ 00:00:00 (24 hours) console.log(convertMsToTime(36900000)); // 👉️ 10:15:00 (10 hours, 15 minutes) console.log(convertMsToTime(15305000)); // 👉️ 04:15:05 (4 hours, 15 minutes, 5 seconds)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
const minute = Math.floor(( milliseconds % (1000 * 60 * 60)) / (1000 * 60)); const second = Math.floor((ms % (1000 * 60)) / 1000);
const Minutes = ((123456/60000).toFixed(2)).replace('.',':'); //Result = 2:06
We divide the number in milliseconds (123456) by 60000 to give us the same number in minutes, which here would be 2.0576.
toFixed(2) - Rounds the number to nearest two decimal places, which in this example gives an answer of 2.06.
You then use replace to swap the period for a colon.
My solution: Input: 11381 (in ms) Output: 00 : 00 : 11.381
timeformatter(time) < console.log(time); let miliSec = String(time%1000); time = (time - miliSec)/1000; let seconds = String(time%60); time = (time - seconds)/60; let minutes = String(time%60); time = (time-minutes)/60; let hours = String(time) while(miliSec.length != 3 && miliSec.length=0) < miliSec = '0'+miliSec; >while(seconds.length != 2 && seconds.length=0) < seconds = '0'+seconds; >while(minutes.length != 2 && minutes.length=0) < minutes = '0'+minutes; >while(hours.length != 2 && hours.length=0) < hours = '0'+hours; >return `$ : $ : $.$` >
const millisToMinutesAndSeconds(millis)=> < const minutes=Math.floor(millis/60/1000) % 60; const seconds=Math.floor(millis/1000) % 60; return minutes + ":" + (seconds
this code will do a better job if you want to show hours, and centiseconds or miliseconds after seconds like 1:02:32.21 and if used in a cell phone the timer will show correct timing even after screen lock.
00:00.00
Convert Milliseconds to Seconds, Minutes, and Hours in JavaScript
JavaScript can sometimes make working with time a bit difficult. In this post, we'll learn how to convert milliseconds to seconds, minutes, and hours using vanilla JavaScript.
We're going to start with a value, in milliseconds, and convert it to seconds, minutes, and hours. The end result should be a string with the number of hours, minutes, and seconds in the HH:MM:SS format.
Convert to Seconds
Let's say you started with this value:
To get the seconds, we can divide the milliseconds by 1000.
Let's use Math.floor to round the number down to the nearest whole number.
Now, this is the number of seconds for the entire duration. We only want the number of seconds left over, so we can use the modulus operator.
Convert to Minutes
Using the same process as we did for seconds, we can get the minutes. This time we have to divide the milliseconds by 1000 , then by 60 , then modulus it by 60 .
Again, we want to use Math.floor to round the minutes down to the nearest whole number.
Convert to Hours
Finally, we can convert the milliseconds to hours. This time we have to divide the milliseconds by 1000 , then by 60 , then by 60 again.
However, this time we need to use modulus 24 since there are 24 hours in a day.
Great, now we have the number of hours, minutes, and seconds. We can use the HH:MM:SS format to display the time.
Formatting the Time
With all three numbers calculated, we can move on to formatting the time.
We can take advantage of JavaScript's type coercion to convert the numbers to strings and then use padStart to add a leading zero to the number if it's less than 10.
From there, we can join the formatted time together with a colon to get our final result.
Now we can just wrap this up in a nice function and call it to get the formatted time.
< const seconds = Math.floor((milliseconds / 1000) % 60); const minutes = Math.floor((milliseconds / 1000 / 60) % 60); const hours = Math.floor((milliseconds / 1000 / 60 / 60) % 24); return [ hours.toString().padStart(2, "0"), minutes.toString().padStart(2, "0"), seconds.toString().padStart(2, "0") ].join(":"); >const formattedTime = formatTime(milliseconds); console.log(formattedTime); // 21:12:09
Conclusion
JavaScript can make it difficult to work with time. However, we learned how to convert milliseconds to seconds, minutes, and hours using vanilla JavaScript and even formatted the time to be in the HH:MM:SS format.
Now you can use that function in any of your JavaScript projects to convert milliseconds to hours, minutes, and seconds!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Give feedback on this page , tweet at us, or join our Discord !
How can I convert milliseconds to "hhmmss" format using javascript?
If you are confident that the period will always be less than a day you could use this one-liner:
new Date(timeDiff).toISOString().slice(11,19) // HH:MM:SS
N.B. This will be wrong if timeDiff is greater than a day.
Convert ms to hh:mm:ss
function millisecondsToHuman(ms) < const seconds = Math.floor((ms / 1000) % 60); const minutes = Math.floor((ms / 1000 / 60) % 60); const hours = Math.floor((ms / 1000 / 3600 ) % 24) const humanized = [ pad(hours.toString(), 2), pad(minutes.toString(), 2), pad(seconds.toString(), 2), ].join(':'); return humanized; >=
pad function ``` function pad(numberString, size) < let padded = numberString; while (padded.length < size) < padded = 0$
function msToHMS( duration ) < var milliseconds = parseInt((duration % 1000) / 100), seconds = parseInt((duration / 1000) % 60), minutes = parseInt((duration / (1000 * 60)) % 60), hours = parseInt((duration / (1000 * 60 * 60)) % 24); hours = (hours
If you want to get more than 24 hours then edit this line: hours = parseInt((duration / (1000 * 60 * 60)));". Removing '% 24'.
Converts milliseconds to a string in the format hh:mm:ss . Here's my version:
function HHMMSSFromMilliseconds(ms) < // 1- Convert to seconds: var seconds = ms / 1000; // 2- Extract hours: var hours = parseInt(seconds / 3600); // 3600 seconds in 1 hour seconds = parseInt(seconds % 3600); // extract the remaining seconds after extracting hours // 3- Extract minutes: var minutes = parseInt(seconds / 60); // 60 seconds in 1 minute // 4- Keep only seconds not extracted to minutes: seconds = parseInt(seconds % 60); // 5 - Format so it shows a leading zero if needed let hoursStr = ("00" + hours).slice(-2); let minutesStr = ("00" + minutes).slice(-2); let secondsStr = ("00" + seconds).slice(-2); return hoursStr + ":" + minutesStr + ":" + secondsStr >let timespan = 23570 * 1000; let formattedTime = HHMMSSFromMilliseconds(timespan); console.log(formattedTime);
Convert millis to DD(days):HH:MM:SS
function formatTime(timeMS) < const [MS_IN_SEC, SEC_IN_DAY, SEC_IN_HOUR, SEC_IN_MIN] = [1000, 86400, 3600, 60]; let seconds = Math.round(Math.abs(timeMS) / MS_IN_SEC); const days = Math.floor(seconds / SEC_IN_DAY); seconds = Math.floor(seconds % SEC_IN_DAY); const hours = Math.floor(seconds / SEC_IN_HOUR); seconds = Math.floor(seconds % SEC_IN_HOUR); const minutes = Math.floor(seconds / SEC_IN_MIN); seconds = Math.floor(seconds % SEC_IN_MIN); const [dd, hh, mm, ss] = [days, hours, minutes, seconds] .map(item =>item
I use this code to convert, (I used as a base some of the codes already presented), I just made a modification so that the minutes 1-9 are presented as 4:00 instead of 04:00 (as in the youtube timer) and it supports more than 24h.
function convertDuration(milliseconds) < const seconds = Math.floor((milliseconds / 1000) % 60); const minutes = Math.floor((milliseconds / 1000 / 60) % 60); const hours = Math.floor((milliseconds / 1000 / 60 / 60)); let formattedTime; if (milliseconds < 60000) < formattedTime = [minutes.toString().padStart(2, "0"), seconds.toString().padStart(2, "0")].join(":"); >else < if (hours === 0) < formattedTime = [minutes.toString(), seconds.toString().padStart(2, "0")].join(":"); >else < formattedTime = [hours.toString(), minutes.toString().padStart(2, "0"), seconds.toString().padStart(2, "0")].join(":"); >> return formattedTime; > // Ex Outputs: console.log(convertDuration(1000)); // Output: 00:01 console.log(convertDuration(10000)); // Output: 00:10 console.log(convertDuration(60000)); // Output: 1:00 console.log(convertDuration(600000)); // Output: 10:00 console.log(convertDuration(3723000)); // Output: 1:02:03 console.log(convertDuration(86400000)); // Output: 24:00:00 console.log(convertDuration(93720000)); // Output: 26:02:00