I am looking to display a video length in the following of two formats:
if less than 59 seconds:
{no_of_sec}
if above 59 seconds:
{no_of_sec} : {no_of_sec}
At the moment this code:
document.getElementById("video2").duration
Returns the following value:
18.133313
I only need need it roundest to the nearest second then in the format above. Without overthinking it, I presume I need to round it. This can be done using Math.round() but it is when the number goes above 59 seconds is where I am struggle.
I plan to put this into an function which would loop through video elements with a class called:
.has--videoDuration
Any ideas?
Given the number of total seconds, you can compute the minute / second components as shown in the snippet below:
var totalSeconds = 18.133313;
var minutes = Math.floor(totalSeconds / 60);
var seconds = Math.floor(totalSeconds % 60);
alert(minutes + ':' + seconds);
Building upon your code:
var duration = Math.round(document.getElementById("video2").duration);
var minutes = ~~(duration / 60); // 1 minute every 60 seconds
var seconds = duration - 60 * minutes; // Remaining seconds
var timeString = minutes ? (minutes + ':' + seconds) : seconds;
I guess the timeString is what you are looking for.
BTW: I would rather use Math.floor for the duration (or ~~), but the exact choice of duration normalization is independent of the rest.
Related
I'm trying to write a logic to convert seconds to the following formats:
HH:MM:SS:MS, where MS is milliseconds
HH:MM:SS;F, where F are the frames
(and not just to HH:MM:SS, therefore this question is different from the others on Stackoverflow)
I have the following logic for getting the HH:MM:SS format currently:
getTime(seconds) {
let h = Math.floor(seconds / 3600);
seconds = seconds % 3600;
let min = Math.floor(seconds / 60);
seconds = Math.floor(seconds % 60);
if (seconds.toString().length < 2) seconds = "0" + seconds;
if (min.toString().length < 2) min = "0" + min;
return (h + ":" + min + ":" + seconds);
}
but how can I get milliseconds or frames?
If seconds is a float, you can take Math.round((seconds - Math.floor(seconds)) * 1000) to get remaining milliseconds. Or Math.round((seconds - Math.floor(seconds)) * fps) where fps is the number of frames per second.
If Your function only takes seconds, then there is no way to get milliseconds out of this information...
You can assume that it is zero milliseconds.
If you want to be accurate to milliseconds, your function should take milliseconds.
var getStringFromMS=(ms,res=[])=>(
[1000,60,60,24].reduce((rest,curr,i)=>(
res[3-i]=rest%curr,Math.floor(rest/curr)
),ms),res.join(":")
);
In action with current time
Simply iterate over the different periods and reduce the milliseconds to days, while doing that the result is stored in res, which can be joined then simply. You may replace 1000 with frames
time -= 50 * 60
I am unsure why time-= is used in the above code snippet? What is the purpose?
Hours is equal to the number of hours in the number of seconds rounded down to a whole number. This difference between hours and the precise number of seconds contains an amount between 0 and just below the maximum number of seconds in 1 hour. To get this, the time in Hours is subtracted from the number of seconds. A similar process follows for the number of minutes.
I will explain line by line to help you get this point:
var seconds = count; //25 * 60 = 1500 (1)
=> just get total seconds before calculating
var hours = Math.floor(seconds / 3600);
=> this is how to calculate hour
seconds -= hours * 3600;
=> this code can be written is easy way seconds = seconds - (hours * 3600);
so the result seconds in this line is the remain second after calculating hours. Now if you get this point the remain code is easily to understand.
var minutes = Math.floor(seconds / 60);
seconds -= minutes * 60
Now, after running this code you can check the result by:
var total_seconds = hours*3600 + minutes*60 + seconds;
The result total_seconds must be equal to value of seconds in the first line of code (1).
This is the basic of programming. If you cannot understand, try to debug it by console.log() to show result. Try yourself is the good way to improve your skill.
var seconds = 7510;
console.log("seconds: "+seconds);
var hours = Math.floor(seconds / 3600);
seconds -= hours * 3600;
console.log("hour: "+hours);
console.log("seconds after calculating hours: "+seconds);
var minutes = Math.floor(seconds / 60);
seconds -= minutes * 60;
console.log("minutes: "+minutes);
console.log("seconds after calculating munites: "+seconds);
var total_seconds = hours*3600 + minutes*60 + seconds;
console.log("total_seconds: "+total_seconds);
I've a problem when running this script for my JavaScript countdown (using this plugin). What it should do is take the starting time, the current time and the end time and display the remaining time.
If I set these values with normal numbers in epoch time everything works just fine, but my question is: How do I set the current time and the start to be the real current one so that the countdown will be dynamic?
I've found this line: Math.round(new Date().getTime()/1000.0);
But I don't know how to make it work, considering I'm running this script at the bottom of my HTML file, before the </html> tag.
This is the script:
<script>
$('.countdown').final_countdown({
start: '[amount Of Time]',
end: '[amount Of Time]',
now: '[amount Of Time]'
});
</script>
This is how I tried to solve it, but it's not working:
//get the current time in unix timestamp seconds
var seconds = Math.round(new Date().getTime()/1000.0);
var endTime = '1388461320';
$('.countdown').final_countdown({
start: '1362139200',
end: endTime,
now: seconds
});
It sounds like you would like to count down from the current time to some fixed point in the future.
The following example counts down and displays the time remaining from now (whenever now might be) to some random time stamp within the next minute.
function startTimer(futureTimeStamp, display) {
var diff;
(function timer() {
// how many seconds are between now and when the count down should end
diff = (futureTimeStamp - Date.now() / 1000) | 0;
if (diff >= 0) {
display(diff);
setTimeout(timer, 1000);
}
}());
}
// wait for the page to load.
window.onload = function() {
var element = document.querySelector('#time'),
now = Date.now() / 1000,
// some random time within the next minute
futureTimeStamp = Math.floor(now + (Math.random() * 60));
// format the display however you wish.
function display(diff) {
var minutes = (diff / 60) | 0,
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
element.innerHTML = minutes + ":" + seconds;
}
startTimer(futureTimeStamp, display);
};
<span id="time"></span>
Also Math.round(new Date().getTime()/1000.0); will give you the number of seconds since the epoch, however it may be a little disingenuous to round the number. I think you would be better served by taking the floor:
var timestamp = Math.floor(Date.now() / 1000)); is probably a better option.
In addition I am not sure why you need the start time, current time and end time. In order to find the remaining number of second you just need to know when the timer should end and the current time.
Currently I am working on JavaScript, jQuery, HTML5 to improve myself. I have a opensourcely coded clock, which I have converted it into a counter (reverse counter).
Problem I am having is, in my setInterval(){...} I have four variables -> second,min,hour, and day. The problem is, when I get the seconds, I get something like 1.155, 2.312, 3.412 (seconds).
My setInterval function is below
setInterval(function(){
//var duration = parseInt(Date.now() /1000 ) - 1365470000;
var futureTime = Date.parse('April 10, 2013 22:00:00');
var duration = (( parseInt(Date.now() - futureTime ) / 1000));
var seconds = duration % 60;
duration = parseInt(duration / 60);
var minutes = duration % 60;
duration = parseInt(duration / 60);
var hours = (duration)%24;
duration = parseInt(duration / 24);
var days = duration % 365;
animation(gVars.green, seconds, 60);
animation(gVars.blue, minutes, 60);
animation(gVars.orange, hours, 24);
animation(gVars.red, days, 365);
},1000);
}
And my output is below for some random time since i use parseInt(Date.now()).
I have to give the link since I don't have enough rep.
http://i.stack.imgur.com/0Zkbi.png
How can I get rid of the decimal point in setInterval(){} functions?
Thanks in advance.
JavaScript offers more convinient API to work with date and time in order to fetch seconds, minutes, hours and days. Try this code:
var duration,
seconds,
minutes,
hours;
duration = new Date((new Date('April 11, 2013 23:00:00')) - (new Date()));
seconds = duration.getSeconds();
minutes = duration.getMinutes();
hours = duration.getHours();
Now you will have integer values in all 4 variables above, without any decimal point.
var seconds = 1234.13;
var seconds = seconds + '';
seconds = seconds.split('.')[0];
console.log(seconds);
I want to make a function either using pure Javascript or also benefiting from jquery to count down to an ending time such as:
//consumes a javascript date object
function countDown(endtimme){
...
}
and it should display in html such as
<div id="time_left_box">
<h1>Time remaining</h1>:
<p>hours left: ..remaining day will be here## <p>
<p>minutes left: ##remaining day will be here## <p>
<p>seconds left: ##remaining day will be here## <p>
</div>
Indeed and it would be even more great if it can refresh itself every second.
I am very naive with javascript and confused about how to approach, any help would be appreciate.
You could use jQuery Countdown
Take a look at this one: http://keith-wood.name/countdown.html
It can be done in JavaScript without plugins.
You need to get the current date time, down to the denominator that is one smaller than what you are displaying. With your example, this would mean you need to get everything down to milliseconds.
var currentTime = new Date(n.getFullYear(), n.getMonth(), n.getDate(), n.getHours(), n.getMinutes(), n.getSeconds(), n.getMilliseconds());
You then find the difference between now and the desired time. This is given to you in milliseconds.
var diff = endtime - currentTime;
Because this is returned in milliseconds you need to convert them into seconds, minutes, hours, days etc... This means establishing how many milliseconds are in each denominator. Then you are able to use mod and divide to return the number needed for each unit. See below.
var miliseconds = 1;
var seconds = miliseconds * 1000;
var minutes = seconds * 60;
var hours = minutes * 60;
var days = hours * 24;
var years = days * 365;
//Getting the date time in terms of units
//Floored so that they go together (to get just year/days/hours etc.. by themselves you need to use Math.round(diff/desired unit);
var numYears = Math.floor(diff / years);
var numDays = Math.floor((diff % years) / days);
var numHours = Math.floor((diff % days) / hours);
var numMinutes = Math.floor((diff % hours) / minutes);
var numSeconds = Math.round((diff % minutes) / seconds);
Once you have the denominators you want to display you can return this to the html page through different methods. For example:
document.getElementById("tyears").innerHTML = numYears;
That sums up your method. However, to make it run on a set interval (which is why you update the HTML display within the JavaScript function) you need to call the following function, giving your function name and provide your interval in terms of milliseconds.
//Call the count down timer function every second (measured in miliseconds)
setInterval(countDown(endtime), 1000);