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);
Related
I'm trying to make a game clock where each game hour are 3 real-time minutes. But I have a hard time wrapping my head around it for some reason.
I've came up with this half working bit, with a loop of 3 minutes for each hour so it's only showing full 'game hours' which I reset once above 23 to start a fresh day.
I guess I would have to update the loop to the accuracy of the game time clock?
var hours;
if (process.argv.length > 2) {
// setting the clock
hours = parseInt(process.argv.slice(2));
}
console.log(hours);
let timerId = setInterval(function() {
hours = hours + 1
if (hours > 23) {
hours = 0;
}
console.log(hours);
}, 3 * 60 * 1000);
Yes, you would have to have a much faster repeating interval, at the level of game-seconds. If one game-hour is 3 real minutes, then game time actually runs 20 times as fast as real time, and so one game-second would last 1/20 real seconds, i.e. 50 milliseconds.
const speed = 20; // how many times faster than real time
let clockDiv = document.querySelector("#clock");
let gameStartTime = 0; // game-milliseconds;
let realStartTime = Date.now(); // real milliseconds
let timerId = setInterval(function() {
let gameTime = gameStartTime + (Date.now() - realStartTime) * speed;
let sec = Math.floor(gameTime / 1000) % 60;
let min = Math.floor(gameTime / 60000) % 60;
let hour = Math.floor(gameTime / 3600000) % 24;
// output in hh:mm:ss format:
clockDiv.textContent = `${hour}:${min}:${sec}`.replace(/\b\d\b/g, "0$&");
}, 50);
<div id="clock"></div>
I'm entirely sure where your problem is, but # 3 mins real time = 1 hour game time, 1 real second = 20 game seconds. 3600 / 180 = 20. You should be able to feed the game seconds into any normal time function to get minutes/hours etc.
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);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have two dates as like one is 2016-02-23 15:12:12 and another one is 2016-02-29 18:16:42 then how to display hh:mm:ss countdown to subtract this two dates using jquery
Please help Thanks in advance
You try like this
var timer;
var compareDate = new Date();
compareDate.setDate(compareDate.getDate() + 7); //just for this demo today + 7 days
timer = setInterval(function() {
timeBetweenDates(compareDate);
}, 1000);
function timeBetweenDates(toDate) {
var dateEntered = toDate;
var now = new Date();
var difference = dateEntered.getTime() - now.getTime();
if (difference <= 0) {
// Timer done
clearInterval(timer);
} else {
var seconds = Math.floor(difference / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
$("#days").text(days);
$("#hours").text(hours);
$("#minutes").text(minutes);
$("#seconds").text(seconds);
}
}
or
you can use countDownjs
http://countdownjs.org/demo.html
Note : better to use 3rd party library because someone wrote code for this you better plug it and start using do not waste time when you have some resource for that.
There are two problems you're looking to solve here.
How do you get the difference between two Date objects in javascript
How do you display that difference in hours, minutes, seconds
Get difference between two Date objects in javascript
First, you need to get the Unix timestamp of each Date object, which is the total number of elapsed seconds from the epoch. Then you can subtract these two values to get the total difference in seconds. To do this we rely on Date's getTime() method, which in javascript returns the number of milliseconds since the epoch.
var start = new Date('2016-02-12 15:12:12');
var end = new Date('2016-02-22 18:16:42');
/* This gives us an integer value of the difference in seconds */
var diff = Math.round((end.getTime() - start.getTime()) / 1000);
Display the difference in hours, minutes, and seconds
The second part requires doing some basic clock arithmetic to get the number of hours, minutes, and seconds from the diff value.
Since there are 3600 seconds in an hour, the total number of hours in this value are Math.floor(diff / 3600). Since there are 60 seconds in every minute, the total number of minutes in this value are Math.floor((diff - (hours * 3600)) / 60), where diff is less the number of hours multiplied by 3600. Subsequently the total number of seconds in this value are just the remainder of the diff, less hours and minutes, from the quotient 60 ((diff - hours * 3600) - (minutes * 60) % 60), which we get from the modulus operator.
function getClock(seconds) {
var hours = Math.floor(diff / 3600);
diff -= hours * 3600
var minutes = Math.floor(diff / 60);
diff -= minutes * 60;
var seconds = diff % 60;
return hours + ":" + minutes + ":" + seconds;
}
Putting it all together
If you want to display countdown clocks like this there are some nifty jquery plugins jQuery Countdown which make this process a lot easier. But I felt it important to explain the details behind the programming, none-the-less.
var date1="2016-02-12 15:12:12";
var date2="2016-02-22 18:16:42";
var d1= date1.split(" ");
d1=d1[1];
var d2= date2.split(" ");
d2=d2[1];
d1=d1.split(":");
d2=d2.split(":");
var hours=d2[0]-d1[0];
var mins=d2[1]-d1[1];
var sec=d2[2]-d1[2];
var countdown=hours+":"+mins+":"+sec;
console.log(countdown);
this will give you time remaining.there are some libs for time countdown.you can use use them
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.
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);