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);
Related
I am trying to generate time slots with a gap of 15min between each one, like the following :
["15:30", "15:45", "16:00", "16:15"...]
So far, I managed to make it. However, if the current time is 15:25 (just an example) the generated array will start from 15:30 what I need instead (in this case) to generate time slots starting from 16:00 meaning that only the first time slot should be approximately away 30 min from the current time.
Currently, I have the following code :
//Used momentJS library
function getTimeStops(end) {
var roundedUp, startTime, endTime, timeStops;
roundedUp = Math.ceil(moment().utc().minute() / 30) * 30;
startTime = moment().utc().set({
minute: roundedUp
});
endTime = moment(end, 'HH:mm');
if (endTime.isBefore(startTime)) {
endTime.add(1, 'day');
}
timeStops = [];
while (startTime <= endTime) {
timeStops.push(new moment(startTime).format('HH:mm'));
startTime.add(15, 'minutes');
}
return timeStops;
}
var timeStops = getTimeStops('02:00');
console.log('timeStops ', timeStops);
You're rounding to the nearest half hour here:
roundedUp = Math.ceil(moment().utc().minute() / 30) * 30;
Round to the nearest hour instead:
roundedUp = Math.ceil(moment().utc().minute() / 60) * 60;
Edit: just realised that the above is wrong and doesn't actually answer your question.
You do need to change your roundedUp value though.
What you need to do is:
Add 30 minutes to the current time
Round it to the closest 15 minute interval
That way - at most - you'll be 7.5 minutes out.
So for step 1, add 30 minutes
var add30mins = moment.utc().add(30, 'minutes')
Now we need to find the closest 15 minute interval.
var roundTo15Mins = Math.round(add30Mins.minute() / 15) * 15;
Then you can plug that into your startTime.
HTH
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.
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'm trying to time a ajax request, but I get random elapsed time:
startTime = new Date();
$.ajax({
...
success: function(response){
endTime = new Date();
timeDiff = endTime - startTime;
elapsed = Math.round(timeDiff % 60);
alert(elapsed + ' seconds elapsed');
}
}
...Like after 2 seconds I get 36 seconds, or 59 seconds, or 1 second etc..
What am I doing wrong here?
Use / instead of %
% is modulo operator.
Proper code to calculate number of seconds between to dates:
(endTime.getTime() - startTime.getTime()) / 1000
Date - Date returns milliseconds. Lets say your request takes one second, so timediff = 1000. You then do a 1000 % 60, which is 40 and not what you want...
I think you want this:
elapsed = Math.round(timeDiff / 1000);
Which will convert milliseconds to seconds.
The modulo operator % return the remainder of a division operation which is not something you appear to be after...
http://en.wikipedia.org/wiki/Modulo_operation
Add a + sign to both versions of new Date():
startTime = +new Date();
That will guarantee that the date is converted into a numerical value (timestamp) which you can do the substraction operation with. It looks like it does work without, but I don't know what that will do some in browsers/versions implementations.
Also as mentioned in other answers, you need to divide the result (which is in miliseconds) by 1000 to get the seconds.