I have this function which formats seconds to time
function secondsToTime(secs){
var hours = Math.floor(secs / (60 * 60));
var divisor_for_minutes = secs % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);
var divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);
return minutes + ":" + seconds;
}
it works great but i need a function to turn milliseconds to time and I cant seem to understand what i need to do to this function to return time in this format
mm:ss.mill
01:28.5568
Lots of unnecessary flooring in other answers. If the string is in milliseconds, convert to h:m:s as follows:
function msToTime(s) {
var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;
return hrs + ':' + mins + ':' + secs + '.' + ms;
}
If you want it formatted as hh:mm:ss.sss then use:
function msToTime(s) {
// Pad to 2 or 3 digits, default is 2
function pad(n, z) {
z = z || 2;
return ('00' + n).slice(-z);
}
var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;
return pad(hrs) + ':' + pad(mins) + ':' + pad(secs) + '.' + pad(ms, 3);
}
console.log(msToTime(55018))
Using some recently added language features, the pad function can be more concise:
function msToTime(s) {
// Pad to 2 or 3 digits, default is 2
var pad = (n, z = 2) => ('00' + n).slice(-z);
return pad(s/3.6e6|0) + ':' + pad((s%3.6e6)/6e4 | 0) + ':' + pad((s%6e4)/1000|0) + '.' + pad(s%1000, 3);
}
// Current hh:mm:ss.sss UTC
console.log(msToTime(new Date() % 8.64e7))
Here is my favourite one-liner solution:
new Date(12345 * 1000).toISOString().slice(11, -1); // "03:25:45.000"
Method Date.prototype.toISOString() returns a string in the simplified extended ISO format (ISO 8601), which is always 24 characters long: YYYY-MM-DDTHH:mm:ss.sssZ. This method is supported in all modern browsers (IE9+) and Node.
This one-liner is limited to a range of one day, which is fine if you use it to format milliseconds up to 24 hours (i.e. ms < 86400000). The following code is able to format correctly any number of milliseconds (shaped in a handy prototype method):
/**
* Convert (milli)seconds to time string (hh:mm:ss[:mss]).
*
* #param Boolean seconds
*
* #return String
*/
Number.prototype.toTimeString = function(seconds) {
var _24HOURS = 8.64e7; // 24*60*60*1000
var ms = seconds ? this * 1000 : this,
endPos = ~(4 * !!seconds), // to trim "Z" or ".sssZ"
timeString = new Date(ms).toISOString().slice(11, endPos);
if (ms >= _24HOURS) { // to extract ["hh", "mm:ss[.mss]"]
var parts = timeString.split(/:(?=\d{2}:)/);
parts[0] -= -24 * Math.floor(ms / _24HOURS);
timeString = parts.join(":");
}
return timeString;
};
console.log( (12345 * 1000).toTimeString() ); // "03:25:45.000"
console.log( (123456 * 789).toTimeString() ); // "27:03:26.784"
console.log( 12345. .toTimeString(true) ); // "03:25:45"
console.log( 123456789. .toTimeString(true) ); // "34293:33:09"
function millisecondsToTime(milli)
{
var milliseconds = milli % 1000;
var seconds = Math.floor((milli / 1000) % 60);
var minutes = Math.floor((milli / (60 * 1000)) % 60);
return minutes + ":" + seconds + "." + milliseconds;
}
Why not use the Date object like this?
let getTime = (milli) => {
let time = new Date(milli);
let hours = time.getUTCHours();
let minutes = time.getUTCMinutes();
let seconds = time.getUTCSeconds();
let milliseconds = time.getUTCMilliseconds();
return hours + ":" + minutes + ":" + seconds + ":" + milliseconds;
}
https://jsfiddle.net/4sdkpso7/6/
function millisecondsToTime(millisecs){
var ms = Math.abs(millisecs) % 1000;
var secs = (millisecs < 0 ? -1 : 1) * ((Math.abs(millisecs) - ms) / 1000);
ms = '' + ms;
ms = '000'.substring(ms.length) + ms;
return secsToTime(secs) + '.' + ms;
}
Here is a filter that use:
app.filter('milliSecondsToTimeCode', function () {
return function msToTime(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 < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
};
});
Just add it to your expression as such
{{milliseconds | milliSecondsToTimeCode}}
Editing RobG's solution and using JavaScript's Date().
function msToTime(ms) {
function addZ(n) {
return (n<10? '0':'') + n;
}
var dt = new Date(ms);
var hrs = dt.getHours();
var mins = dt.getMinutes();
var secs = dt.getSeconds();
var millis = dt.getMilliseconds();
var tm = addZ(hrs) + ':' + addZ(mins) + ':' + addZ(secs) + "." + millis;
return tm;
}
Prons:
simple and clean code; easy to modify for your needs
support any amount of hours (>24 hrs is ok)
format time as 00:00:00.0
You can put it into a helper file
export const msecToTime = ms => {
const milliseconds = ms % 1000
const seconds = Math.floor((ms / 1000) % 60)
const minutes = Math.floor((ms / (60 * 1000)) % 60)
const hours = Math.floor((ms / (3600 * 1000)) % 3600)
return `${hours < 10 ? '0' + hours : hours}:${minutes < 10 ? '0' + minutes : minutes}:${
seconds < 10 ? '0' + seconds : seconds
}.${milliseconds}`
}
This worked for me:
var dtFromMillisec = new Date(secs*1000);
var result = dtFromMillisec.getHours() + ":" + dtFromMillisec.getMinutes() + ":" + dtFromMillisec.getSeconds();
JSFiddle
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
export function getFormattedDateAndTime(startDate) {
if (startDate != null) {
var launchDate = new Date(startDate);
var day = launchDate.getUTCDate();
var month = monthNames[launchDate.getMonth()];
var year = launchDate.getFullYear();
var min = launchDate.getMinutes();
var hour = launchDate.getHours();
var time = launchDate.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true });
return day + " " + month + " " + year + " - " + time + "" ;
}
return "";
}
function msToTime(s) {
var d = new Date(s);
var datestring = ("0" + d.getDate()).slice(-2) + "-" + ("0"+(d.getMonth()+1)).slice(-2) + "-" +
d.getFullYear() + " "
+ ("0" + d.getHours()).slice(-2)
+ ":" + ("0" + d.getMinutes()).slice(-2)
+ ":" + ("0" + d.getSeconds()).slice(-2)
+"."+d.getMilliseconds();
return datestring;
}
output
16-10-2019 18:55:32.605
var
/**
* Parses time in milliseconds to time structure
* #param {Number} ms
* #returns {Object} timeStruct
* #return {Integer} timeStruct.d days
* #return {Integer} timeStruct.h hours
* #return {Integer} timeStruct.m minutes
* #return {Integer} timeStruct.s seconds
*/
millisecToTimeStruct = function (ms) {
var d, h, m, s;
if (isNaN(ms)) {
return {};
}
d = ms / (1000 * 60 * 60 * 24);
h = (d - ~~d) * 24;
m = (h - ~~h) * 60;
s = (m - ~~m) * 60;
return {d: ~~d, h: ~~h, m: ~~m, s: ~~s};
},
toFormattedStr = function(tStruct){
var res = '';
if (typeof tStruct === 'object'){
res += tStruct.m + ' min. ' + tStruct.s + ' sec.';
}
return res;
};
// client code:
var
ms = new Date().getTime(),
timeStruct = millisecToTimeStruct(ms),
formattedString = toFormattedStr(timeStruct);
alert(formattedString);
var secondsToTime = function(duration) {
var date = new Date(duration);
return "%hours:%minutes:%seconds:%milliseconds"
.replace('%hours', date.getHours())
.replace('%minutes', date.getMinutes())
.replace('%seconds', date.getSeconds())
.replace('%milliseconds', date.getMilliseconds());
}
try this function :-
function msToTime(ms) {
var d = new Date(null)
d.setMilliseconds(ms)
return d.toLocaleTimeString("en-US")
}
var ms = 4000000
alert(msToTime(ms))
A possible solution that worked for my case. It turns milliseconds into hh:ss time:
function millisecondstotime(ms) {
var x = new Date(ms);
var y = x.getHours();
if (y < 10) {
y = '0' + y;
}
var z = x.getMinutes();
if (z < 10) {
z = '0' + z;
}
return y + ':' + z;
}
This is the solution I got and working so good!
function msToHuman(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);
return hours + "hrs " minutes + "min " + seconds + "sec " + milliseconds + 'ms';
}
Most of the answers don't cover cases where there is more than 24h. This one does.
I suggest extending Date object:
class SuperDate extends Date {
get raceTime() {
return Math.floor(this/36e5).toString().padStart(2,'0')
+ this.toISOString().slice(13, -1)
}
}
console.log('marathon', new SuperDate(11235200).raceTime)
console.log('ironman', new SuperDate(40521100).raceTime)
console.log('spartathlon', new SuperDate(116239000).raceTime)
console.log('epoch', new SuperDate(new Date()).raceTime)
This approach works great with Firestore Timestamp objects which are similar to what you need:
class SuperDate extends Date {
fromFirestore (timestamp) {
return new SuperDate(timestamp.seconds * 1000 + timestamp.nanoseconds / 1000000)
}
get raceTime() {
return Math.floor(this/36e5).toString().padStart(2,'0')
+ this.toISOString().slice(13, -1)
}
}
const timestamp = {seconds: 11235, nanoseconds: 200000000}
console.log('timestamp', new SuperDate().fromFirestore(timestamp))
console.log('marathon', new SuperDate().fromFirestore(timestamp).raceTime)
Simplest Way
let getTime = (Time)=>{
let Hours = Time.getHours();
let Min = Time.getMinutes();
let Sec = Time.getSeconds();
return `Current time ${Hours} : ${Min} : ${Sec}`;
}
console.log(getTime(new Date()));
An Easier solution would be the following:
var d = new Date();
var n = d.getMilliseconds();
I'm making a stopwatch and out of esthetic reasons I want the output to display: 00:00:00:000. The problem is that when my stopwatch is running I'm having a hard time getting it to except a 0 in front when the value < 10.
window.addEventListener('load', function() {
var display = document.getElementById('display-area');
var toggle = document.getElementById('toggle-button');
var reset = document.getElementById('reset-button');
var ms,
difference,
interval,
hours,
minutes,
seconds,
timer = 0;
function start() {
difference = Date.now();
interval = window.setInterval(update, 10);
timer = 1;
};
function stopp() {
window.clearInterval(interval);
timer = 0;
};
function nullstill() {
ms = 0;
seconds = 0;
minutes = 0;
hours = 0;
display.value = '00:00:00:000';
};
function update() {
ms += elapsedTime();
if (ms >= 1000) {
seconds += 1;
ms = 0;
}
if (seconds >= 60) {
minutes += 1;
seconds = 0;
}
if (minutes >= 60) {
hours += 1;
minutes = 0;
}
display.value = hours + ':' + minutes +':' + seconds +':'+ ms;
};
function elapsedTime() {
var now = Date.now();
elapsed = now - difference;
difference = now;
return elapsed;
};
nullstill();
toggle.addEventListener('click', function() {
console.log(timer);
if (timer != 1) {
start();
} else {
stopp();
}
});
reset.addEventListener('click', function() {
nullstill();
});
});
How do I make it work?
Regards,
An integer will never hold a 0 in front of the number. This is a fairly easy fix. You will just need to use some string concatenation.
display.value = (hours < 10 ? "0"+hours : hours) + ':' + (minutes < 10 ? "0"+minutes : minutes) +':' + (seconds < 10 ? "0"+seconds: seconds) +':'+ ms;
The syntax I have used is called a ternary operator. Here is a little bit about how it works. Basically, it is a simplified if statement which can be used inline.
( condition ? {if true, run this } : {else, run this})
Here's a useful little example that shows you a convenient way to add leading zeros to numbers in Javascript. If you have a number like 53, and want 6 number places (eg 4 leading zeros in the case of 56), you just add (1e6+53+'').slice(-6) and that will give you 000053 because 1e6 means 1 with 6 zeros after it, and slice with a negative number starts from the end and chops out 6 places in this case, so 100000053 becomes 000053
hours=0,minutes=1,seconds=20,ms=7;
document.getElementById('t').innerHTML=
(1e2+hours+'').slice(-2) + ':' +
(1e2+minutes+'').slice(-2) +':' +
(1e2+seconds+'').slice(-2) +':'+
(1e3+ms+'').slice(-3);
<div id='t'></div>
Notice the 1 or 2 leading zeros in the case of ms is handled. And you can adjust the number of leading zeros easily.
This requires string concatenation when the value is less than 10. I would create three separate variables for the hours, minutes and seconds. That way the code is more clean and readable.
var displayHours = (hours >= 10) ? hours : "0" + hours;
var displayMins = (minutes >= 10) ? minutes : "0" + minutes;
var displaySeconds = (seconds >= 10) ? seconds : "0" + seconds;
display.value = displayHours + displayMins + displaySeconds + ":" + ms;
I finally managed to make my 24 hour non-date dependable countdown timer. The purpose of this is that the countdown starts every time someone visits the site. The problem is that when any unit (hours, mins, secs) reaches single digits values display them as such instead of the standard time format (9 minutes instead of 09 minutes, as it should). How can I implement a condition that if a value it's <= 9 it adds a 0 before it?
var count = 86400;
var counter = setInterval(timer, 1000); //1000 will run it every 1 second
function timer() {
count = count - 1;
if (count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
document.getElementById("timer").innerHTML = hours + ":" + minutes + ":" + seconds; // watch for spelling
}
<span id='timer'></span>
Create one function similar to following that does the job for you:
function makeMeTwoDigits(n){
return (n < 10 ? "0" : "") + n;
}
And before printing your numbers call this function:
document.getElementById("timer").innerHTML = makeMeTwoDigits(hours) + ":" + makeMeTwoDigits(minutes) + ":" + makeMeTwoDigits(seconds);
Explanation:
Like #rfornal said, we're checking if the number is less that 10 which means single digit, add '0' and return otherwise add nothing and return.
One point to observe is this won't work if the number is negative.
You can use universal pad function from How to output integers with leading zeros in JavaScript
function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
and change your code to:
document.getElementById("timer").innerHTML = pad(hours,2) + ":" + pad(minutes,2) + ":" + pad(seconds,2);
Try ...
document.getElementById("timer").innerHTML
= (hours<10 ? "0" + hours : hours) + ":"
+ (minutes<10 ? "0" + minutes : minutes) + ":"
+ (seconds<10 ? "0" + seconds : seconds);
Basically, saying if the value is less than 10, place a "0"; else just the value. Another way of saying this is if condition ? then : else ...
An alternate route ... more code would be:
var t_hours, t_minutes, t_seconds;
if (hours<10) {
t_hours = "0" + hours;
} else {
t_hours = hours;
}
if (minutes<10) {
t_minutes = "0" + minutes;
} else {
t_minutes = minutes;
}
if (seconds<10) {
t_seconds = "0" + seconds;
} else {
t_seconds = seconds;
}
document.getElementById("timer").innerHTML
= t_hours + ":" t_minutes + ":" t_seconds;
I am making a online quiz system and i want to convert my timer from seconds to minutes and seconds. Please help me to solve this problem here is my code
<div id="divCounter"></div>
<script type="text/javascript">
if(localStorage.getItem("counter")){
if(localStorage.getItem("counter") <= 0){
var value = 110;
}
else{
var value = localStorage.getItem("counter");
}
}
else{
var value = 10;
}
var counter = function (){
document.getElementById('divCounter').innerHTML = localStorage.getItem("counter");
if(value <= 0){
window.location="http://www.google.com"
}else{
value = parseInt(value)-1;
localStorage.setItem("counter", value);
}
};
var interval = setInterval(function (){counter(value);}, 1000);
Try something like this:
function convert(value) {
return Math.floor(value / 60) + ":" + (value % 60 ? value % 60 : '00')
}
DEMO
value/60 + ":" + value%60, formats to (m)m:ss figure out the right padding
I would suggest you simply use this function (taken from here) which transforms a number of seconds into an string representing the hours, minutes and seconds in format HH:MM:SS:
function secondsToTimeString(seconds) {
var minutes = 0, hours = 0;
if (seconds / 60 > 0) {
minutes = parseInt(seconds / 60, 10);
seconds = seconds % 60;
}
if (minutes / 60 > 0) {
hours = parseInt(minutes / 60, 10);
minutes = minutes % 60;
}
return ('0' + hours).slice(-2) + ':' + ('0' + minutes).slice(-2) + ':' + ('0' + seconds).slice(-2);
}
This question already has answers here:
Adding milliseconds to timer in html
(2 answers)
Closed 8 years ago.
How do i show a countdown timer in html?
Current code:
var count=6000;
var counter=setInterval(timer, 1);; //1000 will run it every 1 second
function timer(){
count=count-1;
if (count <= 0){
clearInterval(counter);
return;
}
document.getElementById("timer").innerHTML=count + " milliseconds"; // watch for spelling
}
Converting seconds to ms
function msToTime(s) {
var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;
return hrs + ':' + mins + ':' + secs + '.' + ms;
}
How would i call out the timer?
still shows the timer as ms. i want it to show up as 99:00 seconds instead of 9900 milliseconds.
Thanks
You can do something like this:
var expires = new Date();
expires.setSeconds(expires.getSeconds() + 60); // set timer to 60 seconds
var counter = setInterval(timer, 1);
function timer() {
var timeDiff = expires - new Date();
if (timeDiff <= 0) {
clearInterval(counter);
document.getElementById("timer").innerHTML = "00:00";
return;
}
var seconds = new Date(timeDiff).getSeconds();
var milliSeconds = (new Date(timeDiff).getMilliseconds() / 10).toFixed(0);
var seconds = seconds < 10 ? "0" + seconds : seconds;
var milliSeconds = milliSeconds < 10 ? "0" + milliSeconds : milliSeconds;
document.getElementById("timer").innerHTML = seconds + ":" + milliSeconds; // watch for spelling
}
Here i set the start time from the javascript Date() function and then calculate the difference from current time in the timer() function.
Check it out here: JSFiddle
If it's JavaScript and has to do with Time I use moment.js
http://momentjs.com
Moment defaults to milliseconds as it's first parameter:
moment(9900).format("mm:ss"); Is 9 seconds, displayed as: 00:09
http://plnkr.co/edit/W2GixF?p=preview
Here's an actually accurate timer (in that it actually shows the correct amount of time left). setInterval will never call every 1 ms regardless of what you ask for because the actually resolution isn't that high. Nor can you rely on consistency because it's not running in a real-time environment. If you want to track time, compare Date objects:
var count=60000;
var start = new Date();
var counter=setInterval(timer, 1); //1000 will run it every 1 second
function timer(){
var left = count - (new Date() - start);
if (left <= 0){
clearInterval(counter);
document.getElementById("timer").innerHTML = msToTime(0) + " seconds";
return;
}
document.getElementById("timer").innerHTML = msToTime(left) + " seconds"; // watch for spelling
}
function msToTime(s) {
var ms = s % 1000;
s = (s - ms) / 1000;
return s + ':' + pad(ms, 3);
}
function pad(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
<div id='timer'></div>
Borrowing from #Cheery's fiddle as a starting point.