I am trying to make the current time of a video display as "Minutes:Seconds:Milliseconds".
I have found a way to extract the milliseconds already from the time, since currentTime already displays as "seconds.milliseconds".
I am wondering if there is a more efficent way to extract the milliseconds from the specified time.
var video = document.querySelector("video");
function showTime() {
var time = video.currentTime;
var m = Math.floor(time / 60);
var s = Math.floor(time % 60);
var ms = (time - Math.floor(time)).toFixed(3).toString();
ms = ms.split(".").slice(1);
if (m < 10) {
m = "0" + m;
}
if (s < 10) {
s = "0" + s;
}
var timeFormat = m + ":" + s + ":" + ms;
return timeFormat;
}
Related
I want to accurately display the difference between two times. The different should be displayed in a format such as mm:ss
methods: {
calcuateTimeDifference: function (startTime, endTime) {
let result = 0;
if (startTime && endTime) {
let start = startTime.split(":");
let end = endTime.split(':');
let startTimeInHrs = (parseFloat(start[0]/3600) + parseFloat(start[1]/60) + parseFloat(start[2]/3600));
let endTimeInHrs = (parseFloat(end[0]/3600) + parseFloat(end[1]/60) + parseFloat(end[2] /3600));
result = endTimeInHrs - startTimeInHrs;
}
return result.toFixed(2);
},
Using this function - the difference between the following times: 16:03:01 - 16:04:01 - I get the result as -32.00.
split the strings on : to get the hours, minutes, and seconds
convert all to seconds and add them to get the total seconds from each time
subtract the two to get the difference in seconds
convert the difference seconds to hours, minutes and seconds using the modules operator(%)
format the result for appropriate display
let start = "16:03:01";
let end = "16:04:05";
let time = calcuateTimeDifference(start, end);
console.log(time);
function calcuateTimeDifference(startTime, endTime) {
let result = 0;
if (startTime && endTime) {
const start = startTime.split(':').map(Number);
const end = endTime.split(':').map(Number);
const startSeconds = (60*60) * start[0] + 60*start[1] + start[2];
const endSeconds = (60*60) * end[0] + 60*end[1] + end[2];
const diffSeconds = endSeconds - startSeconds;
seconds = parseInt((diffSeconds) % 60);
minutes = parseInt((diffSeconds/60) % 60);
hours = parseInt((diffSeconds/(60*60)) % 24);
//append `0` infront if a single digit
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return `${hours}:${minutes}:${seconds}`;
}
console.log("Invalid Input");
}
function calcuateTimeDifference(startTime, endTime) {
let toSeconds = (time) => {
let [h, m, s] = time.split(':');
return h * 360 + m * 60 + +s;
};
let d = Math.abs(toSeconds(startTime) - toSeconds(endTime));
let mm = String(Math.floor(d / 60));
if (mm.length == 1) mm = '0' + mm;
let ss = String(d % 60);
if (ss.length == 1) ss = '0' + ss;
return `${mm}:${ss}`;
}
I need to show the server time on a clock. Below is the code i currently have. I get the server time with Ajax call. The problem is that if the user changes it's local/computer clock it will also update the script's clock which is not ok - it should continue without changing and i'm stuck. I've tried passing the serverTime within the setTimeout so it get's used every time as a reference but no luck with that.
var serverTime = 1490856278000;
var localTime = +Date.now();
var timeDiff = serverTime - localTime;
var realTime;
var date;
var hours;
var minutes;
var seconds;
setInterval(function () {
realTime = +Date.now() + timeDiff;
date = new Date(realTime);
hours = date.getHours();
minutes = date.getMinutes();
seconds = date.getSeconds();
document.getElementById('clock').innerHTML = hours + ':' + minutes + ':' + seconds;
}, 1000);
<div id="clock"></div>
You should be able to compare each realTime with the last one in your setInterval. If the difference is far from the 1000ms that it is supposed to be, do an ajax call to query the server time again and renew the timeDiff.
Also you can try to use performance.now instead of Date.now. The higher resolution is unnecessary and possibly expensive, but MDN states that
unlike Date.now(), the values returned by Performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP)
Using How to create an accurate timer in javascript? and Bergi's answer I prepared an another way. I think you don't have to use the local time at all:
var serverTime = 1490856278000;
var expected = serverTime;
var date;
var hours;
var minutes;
var seconds;
var now = performance.now();
var then = now;
var dt = 0;
var nextInterval = interval = 1000; // ms
setTimeout(step, interval);
function step() {
then = now;
now = performance.now();
dt = now - then - nextInterval; // the drift
nextInterval = interval - dt;
serverTime += interval;
date = new Date(serverTime);
hours = date.getUTCHours();
minutes = date.getUTCMinutes();
seconds = date.getUTCSeconds();
document.getElementById('clock').innerHTML = hours + ':' + minutes + ':' + seconds;
console.log(nextInterval, dt); //Click away to another tab and check the logs after a while
now = performance.now();
setTimeout(step, Math.max(0, nextInterval)); // take into account drift
}
<div id="clock"></div>
The time will change because Date.now(); is getting it's time from the Client machine. There are no AJAX calls in your script.
More Updated with AM & PM
var serverTime = 1490856278000;
var expected = serverTime;
var date;
var h;
var m;
var s;
var now = performance.now();
var then = now;
var dt = 0;
var nextInterval = (interval = 1000);
setTimeout(step, interval);
function step() {
then = now;
now = performance.now();
dt = now - then - nextInterval;
nextInterval = interval - dt;
serverTime += interval;
date = new Date(serverTime);
h = date.getHours();
m = date.getMinutes();
s = date.getSeconds();
var session = "AM";
if (h == 0) {
h = 12;
}
if (h > 12) {
h = h - 12;
session = "PM";
}
h = h < 10 ? "0" + h : h;
m = m < 10 ? "0" + m : m;
s = s < 10 ? "0" + s : s;
var time = h + ":" + m + ":" + s + " " + session;
document.getElementById("NowTime").innerHTML = time;
now = performance.now();
setTimeout(step, Math.max(0, nextInterval));
}
var currentTime = audio.currentTime | 0;
var duration = audio.duration | 0;
it works but,
it shows the audio's total length and current time in only second format
i want to convert the default second value in Minute:Second format
Try this (lightly tested):
var seconds = currentTime % 60;
var foo = currentTime - seconds;
var minutes = foo / 60;
if(seconds < 10){
seconds = "0" + seconds.toString();
}
var fixedCurrentTime = minutes + ":" + seconds;
var currentTime = audio.currentTime | 0;
var duration = audio.duration | 0;
var minutes = "0" + Math.floor(duration / 60);
var seconds = "0" + (duration - minutes * 60);
var dur = minutes.substr(-2) + ":" + seconds.substr(-2);
var minutes = "0" + Math.floor(currentTime / 60);
var seconds = "0" + (currentTime - minutes * 60);
var cur = minutes.substr(-2) + ":" + seconds.substr(-2);
You can simply write the code yourself; it's not as if it's complicated or would ever change:
function pad(num, size) {
var s = num + '';
while (s.length < size) {
s = '0' + s;
}
return s;
}
function format_seconds(secs) {
return Math.floor(secs / 60) + ':' + (pad(secs % 60, 2));
}
dropping my own answer after 5 years and 9 months.
function() {
if(this.myAudio.readyState > 0) {
var currentTime = this.myAudio.currentTime;
var duration = this.myAudio.duration;
var seconds: any = Math.floor(duration % 60);
var foo = duration - seconds;
var min: any = foo / 60;
var minutes: any = Math.floor(min % 60);
var hours: any = Math.floor(min / 60);
if(seconds < 10){
seconds = "0" + seconds.toString();
}
if(hours > 0){
this.audioDuration = hours + ":" + minutes + ":" + seconds;
} else {
this.audioDuration = minutes + ":" + seconds;
}
}
}
I used typescript, hope this helps...
How to parse a given amount of milliseconds (e.g. 125230.41294642858) into a time format like: minutes:seconds?
var ms = 125230.41294642858,
min = 0|(ms/1000/60),
sec = 0|(ms/1000) % 60;
alert(min + ':' + sec);
Try the following
var num = Number(theTextValue);
var seconds = Math.floor(num / 1000);
var minutes = Math.floor(seconds / 60);
var seconds = seconds - (minutes * 60);
var format = minutes + ':' + seconds
Number.prototype.toTime = function(){
var self = this/1000;
var min = (self) << 0;
var sec = (self*60) % 60;
if (sec == 0) sec = '00';
return min + ':' + sec
};
var ms = (new Number('250')).toTime();
console.log(ms);
=> '0:15'
var ms = (new Number('10500')).toTime();
console.log(ms);
=> '10:30'
Even though moment.js does not provide such functionality, if you come here and you are already using moment.js, try this:
function getFormattedMs(ms) {
var duration = moment.duration(ms);
return moment.utc(duration.asMilliseconds()).format("mm:ss");
}
This workaround in moment was introduced in this Issue.
My javascriptcode is working fine when i put alert.I need to Display time in Counter Format(Second decreasing way). Please help me in resolving this issue
<script type="text/javascript">
window.onload = function () {
//alert("request>>>");
var count = 0;
var start_actual_time = document.getElementById("timerStartTime").value;
var end_actual_time = document.getElementById("timerEndTime").value;
start_actual_time = new Date(start_actual_time);
var start_actual_time1 = new Date(start_actual_time.getTime());
start_actual_time1 = new Date(start_actual_time1);
var end_actual_time1 = new Date(end_actual_time);
var hours =end_actual_time1.getHours()- start_actual_time1.getHours();
var minutes = end_actual_time1.getMinutes() - start_actual_time1.getMinutes();
var seconds = end_actual_time1.getSeconds()- start_actual_time1.getSeconds();
seconds = hours * 3600 + minutes * 60 + seconds;
//alert ("seconds >>." +seconds);
timer(seconds);
};
function timer(seconds) {
alert("calling timer");
var s1 = Number(seconds);
var hours = Math.floor(s1 / 3600);
var minutes = Math.floor(s1 % 3600 / 60);
var s = Math.floor(s1 % 3600 % 60);
//alert("sec1" + s);
display = document.querySelector('#time');
var formatted = ((hours < 10)?("0" + hours):hours) + ":" + ((minutes < 10)?("0" + minutes):minutes) + ":" + ((s < 10)?("0" + s):s)
display.textContent = formatted ;
seconds = seconds - 1;
timer(seconds);
}
</script>
The way your code is written creates a
too much recursion
exception for me.
Therefore I have avoided recursive invokes and used javascript setInterval:
var refreshIntervalId = setInterval(function(){ timer(); }, 1000);
When your seconds reach zero, timer is stopped:
if (seconds == -1){
clearInterval(refreshIntervalId);
Link to working fiddle: http://jsfiddle.net/3ggspruf/2/