Javascript clock, change day in advance when clock hits hour - javascript

I'm trying to build a countdown of hours/minutes/seconds that is always 6 days in advance.
The trick is, the countdown should reset at 16:00 everyday, not 24:00, and should display the date in 24h format.
The date should be stated below the clock as "Month (September), Day(13)"
This is what I've came-up with:
function ShowTimes() {
var now = new Date();
now.setDate(now.getDate() + 5)
if (now.getHours() > 14) {
var hrs = 39-now.getHours();
} else {
var hrs = 16-now.getHours();
}
var mins = 59-now.getMinutes();
var secs = 59-now.getSeconds();
var str = '';
str = now.toString();
str += '<br>'+hrs+' hours '+mins+' minutes '+secs+' seconds ';
document.getElementById('countdownToFour').innerHTML = str;
if (hrs < 0) {
hrs = 23-now.getHours();
now.setDate(now.getDate() + 6);
}
}
var _cntDown;
function StopTimes() {
clearInterval(_cntDown);
}
The problem is I have no idea how to set it to 24h time and how to make it reset at 16.00 instead of 24.00. I seemed to have managed to set it 6 days in advance but I'm not so sure...

Because it was hard to understand your code, so I created a new counter:
<html>
<head>
<script type="text/javascript">
var counterIntervalVar;
var howManyDaysAhead = 0;
var finishHours = 16;
var finishMinutes = 0;
var finishSeconds = 0;
function ShowTimes()
{
var str = "";
var now = new Date();//Use current time as start time
//Creating the target time
var dayIncreasion = 1000 * 3600 * 24 * howManyDaysAhead;
var targetDateInMilliSeconds = now.getTime();
var targetDate = new Date(targetDateInMilliSeconds + dayIncreasion);
targetDate.setHours(finishHours);
targetDate.setMinutes(finishMinutes);
targetDate.setSeconds(finishSeconds);
targetDateInMilliSeconds = targetDate.getTime();
//Calculate and show the difference between current time and target time
var timeDifference = targetDateInMilliSeconds - now.getTime();
if (timeDifference >= 0)
{
var hrs = Math.floor(timeDifference / 1000 / 3600);
var mins = Math.floor(timeDifference / 1000 / 60) - (hrs * 60);
sec = Math.floor(timeDifference / 1000) - (hrs * 3600) - (mins * 60);
str += '<br>'+hrs+' hours '+mins+' minutes '+sec+' seconds ';
document.getElementById('countdownToFour').innerHTML = str;
} else {
howManyDaysAhead++;
}
//Give the 'if' query a realistic condition
if (str == 'x')
{
//Stop the loop
window.clearInterval(counterIntervalVar);
}
}
function initCountdown()
{
counterIntervalVar = window.setInterval("ShowTimes()",999);
}
</script>
</head>
<body onLoad="initCountdown()">
<div id="countdownToFour"></div>
</body>
</html>
Hopefully this example works for you or at least leads you to the right way.

Related

Calculate sum of time in JavaScript

I have records in mongodb, time are string.
**Time**
00:10:40
00:40:10
01:10:20
00:43:40
00:42:40
00:30:40
00:54:10
00:47:40
00:50:40
01:05:40
00:45:40
00:51:40
00:36:40
how to calculate sum of whole times?
Is your time strings in an array?
You can use something like this:
var hours = 0;
var minutes = 0;
var seconds = 0;
var sum = '';
var myArray = ["01:40:40","03:50:50"];
var myFunction = function(){
for(var i in myArray){
hours += parseInt(myArray[i].substring(0, 2))
minutes += parseInt(myArray[i].substring(3, 5))
seconds += parseInt(myArray[i].substring(6))
}
if(seconds > 59){
minutes += parseInt(seconds / 60);
seconds = parseInt(seconds % 60);
}
if(minutes > 59){
hours += parseInt(minutes / 60);
minutes = parseInt(minutes % 60);
}
sum = hours + ":" + minutes + ":" + seconds;
console.log(sum);
}
myFunction();
Feel free to ask if you have any other questions.
**This may also work :**
var time1 = "01:00:00";
var time2 = "00:30:00";
var time3 = "00:30:00";
var hour=0;
var minute=0;
var second=0;
var splitTime1= time1.split(':');
var splitTime2= time2.split(':');
var splitTime3= time3.split(':');
hour = parseInt(splitTime1[0])+parseInt(splitTime2[0])+parseInt(splitTime3[0]);
minute = parseInt(splitTime1[1])+parseInt(splitTime2[1])+parseInt(splitTime3[1]);
hour = hour + minute/60;
minute = minute%60;
second = parseInt(splitTime1[2])+parseInt(splitTime2[2])+parseInt(splitTime3[2]);
minute = minute + second/60;
second = second%60;
alert('sum of above time= '+hour+':'+minute+':'+second);

Add a manual start date to my countdown timer, it's using 'new Date();' right now

I'm working on a countdown timer and I have this piece of code right now. I took it from a different post and modified it a bit. I probably don't have to explain how the script works but here is the way I want it to work:
Set a startdate and enddate in the html attributes.
Pass that data into two variables 'dataStart' and 'dataEnd'.
Use the 'dataStart' as startdate and use the 'dataEnd' as enddate.
Countdown from startdate to enddate like this:
If the startdate is in the future, don't start the countdown yet but
let it start as soon as the startdate = the currentdate.
If the startdate is in the past, start the countdown but display the amount
of days, hours, minutes and seconds left from the currentdate to the
enddate.
var dataEnd = document.getElementById('countdown').getAttribute("data-end");
var dataStart = document.getElementById('countdown').getAttribute("data-start");
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
var tiles = document.getElementById('tiles');
var tilesClass = document.getElementById('tiles').classList;
var countLabel = document.getElementById('countdown-label');
var countDiv = document.getElementById('countdown');
function showRemaining() {
var end = new Date(dataEnd);
var start = new Date();
var distance = end - start;
if (distance < 0) {
clearInterval(timer);
// Replaces the countdown tiles with '---' & the label with 'SALE IS OVER'.
tiles.innerHTML = '---';
countLabel.innerHTML ='SALE IS OVER!';
// Sets display to none, so when the countdown is finished it will NOT be visible anymore.
countDiv.style.display = 'none';
return;
} if (distance < _hour ) {
// Removes the Orange background and adds the Red background.
tilesClass.remove('color-half');
tilesClass.add('color-empty');
countLabel.innerHTML ='HURRY! SALE ENDS IN:';
} else {
// Sets display to block, so when the countdown is NOT finished it will be visible.
countDiv.style.display = 'block';
}
var days = pad(Math.floor(distance / _day));
var hours = pad(Math.floor((distance % _day) / _hour));
var minutes = pad(Math.floor((distance % _hour) / _minute));
var seconds = pad(Math.floor((distance % _minute) / _second));
tiles.innerHTML = days + ':';
tiles.innerHTML += hours + ':';
tiles.innerHTML += minutes + ':';
tiles.innerHTML += seconds + '';
}
timer = setInterval(showRemaining, 1000);
function pad(n) {
return (n < 10 ? '0' : '') + n;
}
I have basic javascript knowledge but can't figure this out myself...

Making this JS countdown handle minutes

I have a countdown script that enables me to see how much time there is left until a specific date and time in any given timezone. The script has improved alot from its original state (Much thanks to this community) but it still has some flaws.
The script is currently only able to countdown to a specific hour (Like 2015/12/12 18:00) but NOT to a specific minute (Like 2015/12/12 18:25).
I would like to be able to also specify any given minute of the hour (var minute), but I dont know how. Would greatly apreciate if anyone could help me out.
Edit: The timezone variable (var tz) must be taken into account.
Edit2: Solved the issue I got with the first answer, with this: toDate.setMinutes(minutes-(tz*60));
Full script below:
////////// CONFIGURE THE COUNTDOWN SCRIPT HERE //////////////////
var month = '11'; // '*' for next month, '0' for this month or 1 through 12 for the month
var day = '10'; // Offset for day of month day or + day
var hour = 14; // 0 through 23 for the hours of the day
var tz = -5; // Offset for your timezone in hours from UTC
var lab = 'tzcd'; // The id of the page entry where the timezone countdown is to show
function start() {displayTZCountDown(setTZCountDown(year,month,day,hour,tz),lab);}
// ** The start function can be changed if required **
window.onload = start;
////////// DO NOT EDIT PAST THIS LINE //////////////////
function setTZCountDown(year,month,day,hour,tz)
{
// props to Luke Woodward at Stackoverflow
var now = new Date();
var countdownToYear = now.getFullYear();
var countdownToMonth = now.getMonth();
var countdownToDay = now.getDate();
if (month === '*') {
countdownToMonth += 1;
} else if (month > 0) {
if (month <= now.getMonth()) {
countdownToYear += 1;
}
countdownToMonth = month - 1;
}
if (day.substr(0,1) === '+') {
var day1 = parseInt(day.substr(1), 10);
countdownToDay += day1;
} else {
countdownToDay = day;
}
var toDate = new Date(countdownToYear, countdownToMonth, countdownToDay);
// props to Luke Woodward at Stackoverflow^
toDate.setHours(hour);
toDate.setMinutes(0-(tz*60));
toDate.setSeconds(0);
var fromDate = new Date();
fromDate.setMinutes(fromDate.getMinutes() + fromDate.getTimezoneOffset());
var diffDate = new Date(0);
diffDate.setMilliseconds(toDate - fromDate);
return Math.floor(diffDate.valueOf()/1000);
}
function displayTZCountDown(countdown,tzcd)
{
if (countdown < 0) document.getElementById(tzcd).innerHTML = "<li>0<br><span class='tzcd-format'>day</span></li><li>0<br><span class='tzcd-format'>hours</span></li><li>0<br><span class='tzcd-format'>minutes</span></li><li>0<br><span class='tzcd-format'>seconds</span></li>";
else {var secs = countdown % 60;
if (secs < 10) secs = '0'+secs;
var countdown1 = (countdown - secs) / 60;
var mins = countdown1 % 60;
if (mins < 10) mins = '0'+mins;
countdown1 = (countdown1 - mins) / 60;
var hours = countdown1 % 24;
var days = (countdown1 - hours) / 24;
document.getElementById(tzcd).innerHTML = "<li>" + days + "<br><span class='tzcd-format'>day" + (days == 1 ? '' : 's') + '</span></li>' + "<li>" + hours + "<br><span class='tzcd-format'>hours</span></li> " + "<li>" + mins + "<br><span class='tzcd-format'>minutes</span></li>" +"<li>"+secs+ "<br><span class='tzcd-format'>seconds</span></li>";
setTimeout('displayTZCountDown('+(countdown-1)+',\''+tzcd+'\');',999);
}
}
I wasn't able to test it but this should be it:
////////// CONFIGURE THE COUNTDOWN SCRIPT HERE //////////////////
var month = '11'; // '*' for next month, '0' for this month or 1 through 12 for the month
var day = '10'; // Offset for day of month day or + day
var hour = 14; // 0 through 23 for the hours of the day
var tz = -5; // Offset for your timezone in hours from UTC
var minutes = '10';
var lab = 'tzcd'; // The id of the page entry where the timezone countdown is to show
function start() {displayTZCountDown(setTZCountDown(year,month,day,hour,tz),lab);}
// ** The start function can be changed if required **
window.onload = start;
////////// DO NOT EDIT PAST THIS LINE //////////////////
function setTZCountDown(year,month,day,hour,tz)
{
// props to Luke Woodward at Stackoverflow
var now = new Date();
var countdownToYear = now.getFullYear();
var countdownToMonth = now.getMonth();
var countdownToDay = now.getDate();
if (month === '*') {
countdownToMonth += 1;
} else if (month > 0) {
if (month <= now.getMonth()) {
countdownToYear += 1;
}
countdownToMonth = month - 1;
}
if (day.substr(0,1) === '+') {
var day1 = parseInt(day.substr(1), 10);
countdownToDay += day1;
} else {
countdownToDay = day;
}
var toDate = new Date(countdownToYear, countdownToMonth, countdownToDay);
// props to Luke Woodward at Stackoverflow^
toDate.setHours(hour);
toDate.setMinutes(minutes);
toDate.setSeconds(0);
var fromDate = new Date();
fromDate.setMinutes(fromDate.getMinutes() + fromDate.getTimezoneOffset());
var diffDate = new Date(0);
diffDate.setMilliseconds(toDate - fromDate);
return Math.floor(diffDate.valueOf()/1000);
}
function displayTZCountDown(countdown,tzcd)
{
if (countdown < 0) document.getElementById(tzcd).innerHTML = "<li>0<br><span class='tzcd-format'>day</span></li><li>0<br><span class='tzcd-format'>hours</span></li><li>0<br><span class='tzcd-format'>minutes</span></li><li>0<br><span class='tzcd-format'>seconds</span></li>";
else {var secs = countdown % 60;
if (secs < 10) secs = '0'+secs;
var countdown1 = (countdown - secs) / 60;
var mins = countdown1 % 60;
if (mins < 10) mins = '0'+mins;
countdown1 = (countdown1 - mins) / 60;
var hours = countdown1 % 24;
var days = (countdown1 - hours) / 24;
document.getElementById(tzcd).innerHTML = "<li>" + days + "<br><span class='tzcd-format'>day" + (days == 1 ? '' : 's') + '</span></li>' + "<li>" + hours + "<br><span class='tzcd-format'>hours</span></li> " + "<li>" + mins + "<br><span class='tzcd-format'>minutes</span></li>" +"<li>"+secs+ "<br><span class='tzcd-format'>seconds</span></li>";
setTimeout('displayTZCountDown('+(countdown-1)+',\''+tzcd+'\');',999);
}
}

Countup since a specific date in javascript/jQuery [duplicate]

I want to use a simple countdown timer starting at 30 seconds from when the function is run and ending at 0. No milliseconds. How can it be coded?
var count=30;
var counter=setInterval(timer, 1000); //1000 will run it every 1 second
function timer()
{
count=count-1;
if (count <= 0)
{
clearInterval(counter);
//counter ended, do something here
return;
}
//Do code for showing the number of seconds here
}
To make the code for the timer appear in a paragraph (or anywhere else on the page), just put the line:
<span id="timer"></span>
where you want the seconds to appear. Then insert the following line in your timer() function, so it looks like this:
function timer()
{
count=count-1;
if (count <= 0)
{
clearInterval(counter);
return;
}
document.getElementById("timer").innerHTML=count + " secs"; // watch for spelling
}
I wrote this script some time ago:
Usage:
var myCounter = new Countdown({
seconds:5, // number of seconds to count down
onUpdateStatus: function(sec){console.log(sec);}, // callback for each second
onCounterEnd: function(){ alert('counter ended!');} // final action
});
myCounter.start();
function Countdown(options) {
var timer,
instance = this,
seconds = options.seconds || 10,
updateStatus = options.onUpdateStatus || function () {},
counterEnd = options.onCounterEnd || function () {};
function decrementCounter() {
updateStatus(seconds);
if (seconds === 0) {
counterEnd();
instance.stop();
}
seconds--;
}
this.start = function () {
clearInterval(timer);
timer = 0;
seconds = options.seconds;
timer = setInterval(decrementCounter, 1000);
};
this.stop = function () {
clearInterval(timer);
};
}
So far the answers seem to rely on code being run instantly. If you set a timer for 1000ms, it will actually be around 1008 instead.
Here is how you should do it:
function timer(time,update,complete) {
var start = new Date().getTime();
var interval = setInterval(function() {
var now = time-(new Date().getTime()-start);
if( now <= 0) {
clearInterval(interval);
complete();
}
else update(Math.floor(now/1000));
},100); // the smaller this number, the more accurate the timer will be
}
To use, call:
timer(
5000, // milliseconds
function(timeleft) { // called every step to update the visible countdown
document.getElementById('timer').innerHTML = timeleft+" second(s)";
},
function() { // what to do after
alert("Timer complete!");
}
);
Here is another one if anyone needs one for minutes and seconds:
var mins = 10; //Set the number of minutes you need
var secs = mins * 60;
var currentSeconds = 0;
var currentMinutes = 0;
/*
* The following line has been commented out due to a suggestion left in the comments. The line below it has not been tested.
* setTimeout('Decrement()',1000);
*/
setTimeout(Decrement,1000);
function Decrement() {
currentMinutes = Math.floor(secs / 60);
currentSeconds = secs % 60;
if(currentSeconds <= 9) currentSeconds = "0" + currentSeconds;
secs--;
document.getElementById("timerText").innerHTML = currentMinutes + ":" + currentSeconds; //Set the element id you need the time put into.
if(secs !== -1) setTimeout('Decrement()',1000);
}
// Javascript Countdown
// Version 1.01 6/7/07 (1/20/2000)
// by TDavid at http://www.tdscripts.com/
var now = new Date();
var theevent = new Date("Sep 29 2007 00:00:01");
var seconds = (theevent - now) / 1000;
var minutes = seconds / 60;
var hours = minutes / 60;
var days = hours / 24;
ID = window.setTimeout("update();", 1000);
function update() {
now = new Date();
seconds = (theevent - now) / 1000;
seconds = Math.round(seconds);
minutes = seconds / 60;
minutes = Math.round(minutes);
hours = minutes / 60;
hours = Math.round(hours);
days = hours / 24;
days = Math.round(days);
document.form1.days.value = days;
document.form1.hours.value = hours;
document.form1.minutes.value = minutes;
document.form1.seconds.value = seconds;
ID = window.setTimeout("update();", 1000);
}
<p><font face="Arial" size="3">Countdown To January 31, 2000, at 12:00: </font>
</p>
<form name="form1">
<p>Days
<input type="text" name="days" value="0" size="3">Hours
<input type="text" name="hours" value="0" size="4">Minutes
<input type="text" name="minutes" value="0" size="7">Seconds
<input type="text" name="seconds" value="0" size="7">
</p>
</form>
Just modified #ClickUpvote's answer:
You can use IIFE (Immediately Invoked Function Expression) and recursion to make it a little bit more easier:
var i = 5; //set the countdown
(function timer(){
if (--i < 0) return;
setTimeout(function(){
console.log(i + ' secs'); //do stuff here
timer();
}, 1000);
})();
var i = 5;
(function timer(){
if (--i < 0) return;
setTimeout(function(){
document.getElementsByTagName('h1')[0].innerHTML = i + ' secs';
timer();
}, 1000);
})();
<h1>5 secs</h1>
Expanding upon the accepted answer, your machine going to sleep, etc. may delay the timer from working. You can get a true time, at the cost of a little processing. This will give a true time left.
<span id="timer"></span>
<script>
var now = new Date();
var timeup = now.setSeconds(now.getSeconds() + 30);
//var timeup = now.setHours(now.getHours() + 1);
var counter = setInterval(timer, 1000);
function timer() {
now = new Date();
count = Math.round((timeup - now)/1000);
if (now > timeup) {
window.location = "/logout"; //or somethin'
clearInterval(counter);
return;
}
var seconds = Math.floor((count%60));
var minutes = Math.floor((count/60) % 60);
document.getElementById("timer").innerHTML = minutes + ":" + seconds;
}
</script>
For the sake of performances, we can now safely use requestAnimationFrame for fast looping, instead of setInterval/setTimeout.
When using setInterval/setTimeout, if a loop task is taking more time than the interval, the browser will simply extend the interval loop, to continue the full rendering. This is creating issues. After minutes of setInterval/setTimeout overload, this can freeze the tab, the browser or the whole computer.
Internet devices have a wide range of performances, so it's quite impossible to hardcode a fixed interval time in milliseconds!
Using the Date object, to compare the start Date Epoch and the current. This is way faster than everything else, the browser will take care of everything, at a steady 60FPS (1000 / 60 = 16.66ms by frame) -a quarter of an eye blink- and if the task in the loop is requiring more than that, the browser will drop some repaints.
This allow a margin before our eyes are noticing (Human = 24FPS => 1000 / 24 = 41.66ms by frame = fluid animation!)
https://caniuse.com/#search=requestAnimationFrame
/* Seconds to (STRING)HH:MM:SS.MS ------------------------*/
/* This time format is compatible with FFMPEG ------------*/
function secToTimer(sec){
const o = new Date(0), p = new Date(sec * 1000)
return new Date(p.getTime()-o.getTime()).toString().split(" ")[4] + "." + p.getMilliseconds()
}
/* Countdown loop ----------------------------------------*/
let job, origin = new Date().getTime()
const timer = () => {
job = requestAnimationFrame(timer)
OUT.textContent = secToTimer((new Date().getTime() - origin) / 1000)
}
/* Start looping -----------------------------------------*/
requestAnimationFrame(timer)
/* Stop looping ------------------------------------------*/
// cancelAnimationFrame(job)
/* Reset the start date ----------------------------------*/
// origin = new Date().getTime()
span {font-size:4rem}
<span id="OUT"></span>
<br>
<button onclick="origin = new Date().getTime()">RESET</button>
<button onclick="requestAnimationFrame(timer)">RESTART</button>
<button onclick="cancelAnimationFrame(job)">STOP</button>
You can do as follows with pure JS. You just need to provide the function with the number of seconds and it will do the rest.
var insertZero = n => n < 10 ? "0"+n : ""+n,
displayTime = n => n ? time.textContent = insertZero(~~(n/3600)%3600) + ":" +
insertZero(~~(n/60)%60) + ":" +
insertZero(n%60)
: time.textContent = "IGNITION..!",
countDownFrom = n => (displayTime(n), setTimeout(_ => n ? sid = countDownFrom(--n)
: displayTime(n), 1000)),
sid;
countDownFrom(3610);
setTimeout(_ => clearTimeout(sid),20005);
<div id="time"></div>
Based on the solution presented by #Layton Everson I developed a counter including hours, minutes and seconds:
var initialSecs = 86400;
var currentSecs = initialSecs;
setTimeout(decrement,1000);
function decrement() {
var displayedSecs = currentSecs % 60;
var displayedMin = Math.floor(currentSecs / 60) % 60;
var displayedHrs = Math.floor(currentSecs / 60 /60);
if(displayedMin <= 9) displayedMin = "0" + displayedMin;
if(displayedSecs <= 9) displayedSecs = "0" + displayedSecs;
currentSecs--;
document.getElementById("timerText").innerHTML = displayedHrs + ":" + displayedMin + ":" + displayedSecs;
if(currentSecs !== -1) setTimeout(decrement,1000);
}
// Javascript Countdown
// Version 1.01 6/7/07 (1/20/2000)
// by TDavid at http://www.tdscripts.com/
var now = new Date();
var theevent = new Date("Nov 13 2017 22:05:01");
var seconds = (theevent - now) / 1000;
var minutes = seconds / 60;
var hours = minutes / 60;
var days = hours / 24;
ID = window.setTimeout("update();", 1000);
function update() {
now = new Date();
seconds = (theevent - now) / 1000;
seconds = Math.round(seconds);
minutes = seconds / 60;
minutes = Math.round(minutes);
hours = minutes / 60;
hours = Math.round(hours);
days = hours / 24;
days = Math.round(days);
document.form1.days.value = days;
document.form1.hours.value = hours;
document.form1.minutes.value = minutes;
document.form1.seconds.value = seconds;
ID = window.setTimeout("update();", 1000);
}
<p><font face="Arial" size="3">Countdown To January 31, 2000, at 12:00: </font>
</p>
<form name="form1">
<p>Days
<input type="text" name="days" value="0" size="3">Hours
<input type="text" name="hours" value="0" size="4">Minutes
<input type="text" name="minutes" value="0" size="7">Seconds
<input type="text" name="seconds" value="0" size="7">
</p>
</form>
My solution works with MySQL date time formats and provides a callback function. on complition.
Disclaimer: works only with minutes and seconds, as this is what I needed.
jQuery.fn.countDownTimer = function(futureDate, callback){
if(!futureDate){
throw 'Invalid date!';
}
var currentTs = +new Date();
var futureDateTs = +new Date(futureDate);
if(futureDateTs <= currentTs){
throw 'Invalid date!';
}
var diff = Math.round((futureDateTs - currentTs) / 1000);
var that = this;
(function countdownLoop(){
// Get hours/minutes from timestamp
var m = Math.floor(diff % 3600 / 60);
var s = Math.floor(diff % 3600 % 60);
var text = zeroPad(m, 2) + ':' + zeroPad(s, 2);
$(that).text(text);
if(diff <= 0){
typeof callback === 'function' ? callback.call(that) : void(0);
return;
}
diff--;
setTimeout(countdownLoop, 1000);
})();
function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
}
// $('.heading').countDownTimer('2018-04-02 16:00:59', function(){ // on complete})
var hr = 0;
var min = 0;
var sec = 0;
var count = 0;
var flag = false;
function start(){
flag = true;
stopwatch();
}
function stop(){
flag = false;
}
function reset(){
flag = false;
hr = 0;
min = 0;
sec = 0;
count = 0;
document.getElementById("hr").innerHTML = "00";
document.getElementById("min").innerHTML = "00";
document.getElementById("sec").innerHTML = "00";
document.getElementById("count").innerHTML = "00";
}
function stopwatch(){
if(flag == true){
count = count + 1;
setTimeout( 'stopwatch()', 10);
if(count ==100){
count =0;
sec = sec +1;
}
}
if(sec ==60){
min = min +1 ;
sec = 0;
}
if(min == 60){
hr = hr +1 ;
min = 0;
sec = 0;
}
var hrs = hr;
var mins = min;
var secs = sec;
if(hr<10){
hrs ="0" + hr;
}
if(min<10){
mins ="0" + min;
}
if(sec<10){
secs ="0" + sec;
}
document.getElementById("hr").innerHTML = hrs;
document.getElementById("min").innerHTML = mins;
document.getElementById("sec").innerHTML = secs;
document.getElementById("count").innerHTML = count;
}

Calculate Time Difference with JavaScript

I have two HTML input boxes, that need to calculate the time difference in JavaScript onBlur (since I need it in real time) and insert the result to new input box.
Format example: 10:00 & 12:30 need to give me: 02:30
Thanks!
Here is one possible solution:
function diff(start, end) {
start = start.split(":");
end = end.split(":");
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);
// If using time pickers with 24 hours format, add the below line get exact hours
if (hours < 0)
hours = hours + 24;
return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes;
}
DEMO: http://jsfiddle.net/KQQqp/
Try This
var dif = ( new Date("1970-1-1 " + end-time) - new Date("1970-1-1 " + start-time) ) / 1000 / 60 / 60;
tl;dr
One off run
const t1 = new Date(1579876543210) // your initial time
const t2 = new Date(1579987654321) // your later time
const diff = t2-t1
const SEC = 1000, MIN = 60 * SEC, HRS = 60 * MIN
const humanDiff = `${Math.floor(diff/HRS)}:${Math.floor((diff%HRS)/MIN).toLocaleString('en-US', {minimumIntegerDigits: 2})}:${Math.floor((diff%MIN)/SEC).toLocaleString('en-US', {minimumIntegerDigits: 2})}.${Math.floor(diff % SEC).toLocaleString('en-US', {minimumIntegerDigits: 4, useGrouping: false})}`
console.log("humanDiff:", humanDiff)
// > humanDiff: 30:51:51.0111
As a function
function humanDiff (t1, t2) {
const diff = Math.max(t1,t2) - Math.min(t1,t2)
const SEC = 1000, MIN = 60 * SEC, HRS = 60 * MIN
const hrs = Math.floor(diff/HRS)
const min = Math.floor((diff%HRS)/MIN).toLocaleString('en-US', {minimumIntegerDigits: 2})
const sec = Math.floor((diff%MIN)/SEC).toLocaleString('en-US', {minimumIntegerDigits: 2})
const ms = Math.floor(diff % SEC).toLocaleString('en-US', {minimumIntegerDigits: 4, useGrouping: false})
return `${hrs}:${min}:${sec}.${ms}`
}
const t1 = new Date(1579876543210)
const t2 = new Date(1579987654321)
console.log("humanDiff(t1, t2):", humanDiff(t1, t2))
// > humanDiff: 30:51:51.0111
Explanation
Adjust humanDiff for your maximum and minimum reportable increments and formatting needs:
const t1 = new Date(1579876543210) // Set your initial time (`t1`)
const t2 = new Date(1579986654321) // , conclusion time (`t2`), and
const diff = t2-t1 // calculate their difference in milliseconds
console.log(" t2:", t2.toISOString()) // > t2: 2020-01-25T21:27:34.321Z
console.log(" t1:", t1.toISOString()) // > t1: 2020-01-24T14:35:43.210Z
console.log(" diff:", diff) // > diff: 111111111
// Set your constant time values for easy readability
const SEC = 1000
const MIN = 60 * SEC
const HRS = 60 * MIN
/* For a given unit
1) disregard any previously relevant units, e.g. to calculate minutes, we can
disregard all hours & focus on only the remainder - `(diff%HRS)`
2) divide the remainder by the given unit, e.g. for minutes, `(diff%HRS)/MIN`
3) disregard any remainder, e.g. again for minutes, `Math.floor((diff%HRS)/MIN)`
NOTE: for your maximum unit (HRS in the examples below) you probably _don't_
want to disregard high values, e.g. If the difference is >24 hrs and something,
you should either include a DAYS value, or simply display 30 hrs */
let hrs = Math.floor(diff/HRS)
let min = Math.floor((diff%HRS)/MIN)
let sec = Math.floor((diff%MIN)/SEC)
let ms = Math.floor(diff % SEC) // just the remainder
// BUT ms IS NOT ACTUALLY CORRECT, see humanDiff_3 for the fix ;-)
let humanDiff_1 = `${hrs}:${min}:${sec}.${ms}`
console.log("humanDiff_1:", humanDiff_1)
// > humanDiff_1: 30:51:51.111
sec = Math.round((diff%MIN)/SEC) // can also just round the last unit
const humanDiff_2 = `${hrs} hrs ${min} mins & ${sec} secs`
console.log("humanDiff_2:", humanDiff_2)
// > humanDiff_2: 30 hrs 51 mins & 51 secs
/* To ensure a set number of digits, format the numbers with `toLocaleString`'s
`minimumIntegerDigits`, if more than 3 digits, also use its `useGrouping` */
hrs = Math.floor(diff/HRS)
min = Math.floor((diff%HRS)/MIN).toLocaleString('en-US', {minimumIntegerDigits: 2})
sec = Math.floor((diff%MIN)/SEC).toLocaleString('en-US', {minimumIntegerDigits: 2})
ms = Math.floor(diff % SEC).toLocaleString('en-US', {minimumIntegerDigits: 4, useGrouping: false})
const humanDiff_3 = `${hrs}:${min}:${sec}.${ms}`
console.log("humanDiff_3:", humanDiff_3)
// > humanDiff_3: 30:51:51.0111
// NOTE: milliseconds are now 4 digits
This solution works for calculating diff between to separate military times
Example format: start = 23:00 / end = 02:30
function diff(start, end) {
start = start.split(":");
end = end.split(":");
if(Number(start[0]) > Number(end[0]) ) {
var num = Number(start[0])
var countTo = Number(end[0]);
var count = 0;
for (var i = 1; num != countTo;) {
num = num + i
if(num > 24) {
num = 0
}
count++
}
var hours = count - 1;
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
if(startDate.getMinutes() > endDate.getMinutes()) {
var hours = count - 2;
var diff = 60 - (startDate.getMinutes() - endDate.getMinutes());
} else {
var diff = endDate.getMinutes() - startDate.getMinutes();
}
var minutes = diff
} else {
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);
}
var returnValue = (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes
return returnValue;
}
Well this work almost great. Now use this code to calculate: 23:50 - 00:10 And see what you get.Or even 23:30 - 01:30. That's a mess.
Because getting the answer the other way in php is:
$date1 = strtotime($_POST['started']);
$date2 = strtotime($_POST['ended']);
$interval = $date2 - $date1;
$playedtime = $interval / 60;
But still, it works like yours.
I guess have to bring in the dates aswell?
And again: My hard research and development helped me.
if (isset($_POST['calculate'])) {
$d1 = $_POST['started'];
$d2 = $_POST['ended'];
if ($d2 < $d1) {
$date22 = date('Y-m-');
$date222 = date('d')-1;
$date2 = $date22."".$date222;
} else {
$date2 = date('Y-m-d');
}
$date1 = date('Y-m-d');
$start_time = strtotime($date2.' '.$d1);
$end_time = strtotime($date1.' '.$d2); // or use date('Y-m-d H:i:s') for current time
$playedtime = round(abs($start_time - $end_time) / 60,2);
}
And that's how you calculate time over to the next day.
//edit. First i had date1 jnd date2 switched. I need to -1 because this calculation only comes on next day and the first date vas yesterday.
After improving and a lot of brain power with my friend we came up to this:
$begin=mktime(substr($_GET["start"], 0,2),substr($_GET["start"], 2,2),0,1,2,2003);
$end=mktime(substr($_GET["end"], 0,2),substr($_GET["end"], 2,2),0,1,3,2003);
$outcome=($end-$begin)-date("Z");
$minutes=date("i",$outcome)+date("H",$outcome)*60; //Echo minutes only
$hours = date("H:i", $outcome); //Echo time in hours + minutes like 01:10 or something.
So you actually need only 4 lines of code to get your result. You can take only minutes or show full time (like difference is 02:32) 2 hours and 32 minutes.
What's most important: Still you can calculate overnight in 24 hour clock aka: Start time 11:50PM to let's say 01:00 AM (in 24 hour clock 23:50 - 01:00) because in 12 hour mode it works anyway.
What's most important: You don't have to format your input. You can use just plain 2300 as 23:00 input. This script will convert text field input to correct format by itself.
Last script uses standard html form with method="get" but you can convert it to use POST method as well.
This is an updated version of one that was already submitted. It is with the seconds.
function diff(start, end) {
start = start.split(":");
end = end.split(":");
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * (1000 * 60 * 60);
var minutes = Math.floor(diff / 1000 / 60);
diff -= minutes * (1000 * 60);
var seconds = Math.floor(diff / 1000);
// If using time pickers with 24 hours format, add the below line get exact hours
if (hours < 0)
hours = hours + 24;
return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes + (seconds<= 9 ? "0" : "") + seconds;
}
My Updated Version:
Allows for you to convert the dates into milliseconds and go off of that instead of splitting.
Example Does -- Years/Months/Weeks/Days/Hours/Minutes/Seconds
Example: https://jsfiddle.net/jff7ncyk/308/
With seconds you provided is not get result to me please find my updated function giving you the correct seconds here - By Dinesh J
function diff(start, end) {
start = start.split(":");
end = end.split(":");
var startDate = new Date(0, 0, 0, start[0], start[1],start[2], 0);
var endDate = new Date(0, 0, 0, end[0], end[1],end[2], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);
var seconds = Math.floor(diff / 1000)-120;
// If using time pickers with 24 hours format, add the below line get exact hours
if (hours < 0)
hours = hours + 24;
return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes+ ":" + (seconds <= 9 ? "0" : "") + seconds;
}
Depending on what you allow to enter, this one will work. There may be some boundary issues if you want to allow 1am to 1pm
NOTE: This is NOT using a date objects or moment.js
function pad(num) {
return ("0"+num).slice(-2);
}
function diffTime(start,end) {
var s = start.split(":"), sMin = +s[1] + s[0]*60,
e = end.split(":"), eMin = +e[1] + e[0]*60,
diff = eMin-sMin;
if (diff<0) { sMin-=12*60; diff = eMin-sMin }
var h = Math.floor(diff / 60),
m = diff % 60;
return "" + pad(h) + ":" + pad(m);
}
document.getElementById('button').onclick=function() {
document.getElementById('delay').value=diffTime(
document.getElementById('timeOfCall').value,
document.getElementById('timeOfResponse').value
);
}
<input type="time" id="timeOfCall">
<input type="time" id="timeOfResponse">
<button type="button" id="button">CLICK</button>
<input type="time" id="delay">
calTimeDifference(){
this.start = dailyattendance.InTime.split(":");
this.end = dailyattendance.OutTime.split(":");
var time1 = ((parseInt(this.start[0]) * 60) + parseInt(this.start[1]))
var time2 = ((parseInt(this.end[0]) * 60) + parseInt(this.end[1]));
var time3 = ((time2 - time1) / 60);
var timeHr = parseInt(""+time3);
var timeMin = ((time2 - time1) % 60);
}
TimeCount = function()
{
t++;
var ms = t;
if (ms == 99)
{
s++;
t = 0;
if ( s == 60)
{
m++;
s = 0;
}
}
Dis_ms = checkTime(ms);
Dis_s = checkTime(s);
Dis_m = checkTime(m);
document.getElementById("time_val").innerHTML = Dis_m + ":" + Dis_s+ ":" + Dis_ms;
}
function checkTime(i)
{
if (i<10) {
i = "0" + i;
}
return i;
}
Try this: actually this a problem from codeeval.com
I solved it in this way .
This program takes a file as the argument so i used a little node js to read the file.
Here is my code.
var fs = require("fs");
fs.readFileSync(process.argv[2]).toString().split('\n').forEach(function (line) {
if (line !== "") {
var arr = line.split(" ");
var arr1 = arr[0].split(":");
var arr2 = arr[1].split(":");
var time1 = parseInt(arr1[0])*3600 + parseInt(arr1[1])*60 + parseInt(arr1[2]);
var time2 = parseInt(arr2[0])*3600 + parseInt(arr2[1])*60 + parseInt(arr2[2]);
var dif = Math.max(time1,time2) - Math.min(time1,time2);
var ans = [];
ans[0] = Math.floor(dif/3600);
if(ans[0]<10){ans[0] = "0"+ans[0]}
dif = dif%3600;
ans[1] = Math.floor(dif/60);
if(ans[1]<10){ans[1] = "0"+ans[1]}
ans[2] = dif%60;
if(ans[2]<10){ans[2] = "0"+ans[2]}
console.log(ans.join(":"));
}
});
We generally need time difference to estimate time taken by I/O operations, SP call etc, the simplest solution for NodeJs (the console is in callback- async execution) is following:
var startTime = new Date().getTime();
//This will give you current time in milliseconds since 1970-01-01
callYourExpectedFunction(param1, param2, function(err, result){
var endTime = new Date().getTime();
//This will give you current time in milliseconds since 1970-01-01
console.log(endTime - startTime)
//This will give you time taken in milliseconds by your function
if(err){
}
else{
}
})

Categories

Resources