Difference between two html time inputs - javascript

I try to calculate the difference between two HTML time input elements. At the moment that one of the times is changed, there has to be recalculated, unfortunately I can not do this for each other. Who can help me?
<input type="time" id="start" value="10:00" >
<input type="time" id="end" value="12:30" >
<input id="diff">
<script>
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
document.getElementById("start").onchange = function() {diff(start,end)};
document.getElementById("end").onchange = function() {diff(start,end)};
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);
return (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes;
}
document.getElementById("diff").value = diff(start, end);
</script>

This time difference code is amazing! So if all you need is for it to update itself, I copied and slightly remodeled your code for you. Again, your code is amazing :)
<input type="time" id="start" value="10:00" >
<input type="time" id="end" value="12:30" >
<input id="diff">
<script>
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
document.getElementById("start").onchange = function() {diff(start,end)};
document.getElementById("end").onchange = function() {diff(start,end)};
function diff(start, end) {
start = document.getElementById("start").value; //to update time value in each input bar
end = document.getElementById("end").value; //to update time value in each input bar
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);
return (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes;
}
setInterval(function(){document.getElementById("diff").value = diff(start, end);}, 1000); //to update time every second (1000 is 1 sec interval and function encasing original code you had down here is because setInterval only reads functions) You can change how fast the time updates by lowering the time interval
</script>
Is this what you want, if not, tell me, I'll be happy to help with this magnificent code :)

With your code, you get the value of start and end just one time..you have to get the value each time you want to calculate the difference
try to do
document.getElementById("start").onchange = function() {
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
diff(start,end)};
and the same thing for the other element.

//You can create a function like this that returns the difference between two times in hours it accepts as parameters string in format time "hh:mm";
function timeDiffInHours(time1, time2){
time1Arr = time1.split(":");
time1InMinutes = parseInt(time1Arr[0])*60+parseInt(time1Arr[1]);
time2Arr = time2.split(":");
time2InMinutes = parseInt(time2Arr[0])*60+parseInt(time2Arr[1]);
diff = time2InMinutes - time1InMinutes;
return Math.floor(100*diff/60)/100;
}
console.log(timeDiffInHours("08:30","18:30");
//Response : 10

Related

JavaScript to auto-calculate man-hours in 24-time for Adobe Form Field?

I run a landscape crew and instead of filling out our forms manually I would like to do it via cellphone and have the times auto-calculated in the form fields. I'm not familiar with JavaScript and need some assistance in getting the correct code in order to calculate the crew times and total site man-hours without this error when I change the times. Note: I will use 24-hour time.
I tried a few different JavaScript snippets I discovered and though they work I am getting a format error when manipulating the time input. Any suggestions on how to script this into Adobe?
To generate the employee times I use the code below:
UPDATE EDIT THIS IS GENERATING INCORRECT TIMES:
// start
var start = this.getField("Monday Site #1 Start Time").value;
var startArr = start.split(":");
// finish
var finish = this.getField("Monday Site #1 Depart Time").value;
var finishArr = finish.split(":");
// difference
var hourDiff = Math.abs(finishArr[0] - startArr[0]);
var minDiff = Math.floor((Math.abs(finishArr[1] - startArr[1]) / 60)*100);
if (minDiff.toString().length == 1)
minDiff = '0' + minDiff;
var output = hourDiff + "." + minDiff;
event.value = output;
if ((event.value == "") || (event.value == Infinity) || isNaN(event.value)) {
event.value = "";}
To calculate the total site time (total manhours for the specific site) I used this:
var t1 = this.getField("WS1 Total").value;
var t2 = this.getField("WS1 Total").value;
var t3 = this.getField("WS1 Total").value;
event.value = t1+t2+t3
You can calculate the elapsed time between two Javascript Date objects in milliseconds like this:
function timeDiff(startTime, endTime) {
var startArr = startTime.split(":");
var endArr = endTime.split(":");
var startDate = new Date(0, 0, 0, startArr[0], startArr[1], 0);
var endDate = new Date(0, 0, 0, endArr[0], endArr[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);
return hours + ":" + (minutes < 9 ? "0" : "") + minutes;
}
console.log(timeDiff('6:24', '8:13')) // 1:49
Or if you want to return hours as decimal.
function timeDiff(startTime, endTime) {
var startArr = startTime.split(":");
var endArr = endTime.split(":");
var startDate = new Date(0, 0, 0, startArr[0], startArr[1], 0);
var endDate = new Date(0, 0, 0, endArr[0], endArr[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = diff / 1000 / 60 / 60;
return hours.toFixed(2)
}
console.log(timeDiff('6:24', '8:13')) // 1.82
I'm guessing that you can then do something like this:
var finish = this.getField("Monday Site #1 Depart Time").value;
var start = this.getField("Monday Site #1 Start Time").value;
this.getField("MS1T").value = timeDiff(start, finish);
This worked, with a tweak for NaN:
var start = this.getField("Monday Site #1 Depart Time").value;
var finish = this.getField("Monday Site #2 Depart Time").value;
this.getField("MS1 Total").value = timeDiff(start, finish);
if ((event.value == "") || (event.value == Infinity) || isNaN(event.value)) {event.value = "";}

Javascript Count Up Timer

I am trying to make a javascript timer that when initiated, starts counting up. The timer is just a visual reference from when a start button is clicked to when the end button is clicked.
I found a plugin online which works perfectly for counting down but I am trying to modify it to count up.
I hard coded a date way in the future. I am now trying to get the timer to start counting up to that date. This will be reset every time the start button is clicked.
This is the function I am working with. it works perfectly to count down but I cant figure out how to reverse it.
I thought it was something with how the differece was calculated but I believe it actually happens in the //calculate dates section.
Is there an easy way to reverse this math and have it count up instead?
Fiddle: http://jsfiddle.net/xzjoxehj/
var currentDate = function () {
// get client's current date
var date = new Date();
// turn date to utc
var utc = date.getTime() + (date.getTimezoneOffset() * 60000);
// set new Date object
var new_date = new Date(utc + (3600000*settings.offset))
return new_date;
};
function countdown () {
var target_date = new Date('12/31/2020 12:00:00'), // Count up to this date
current_date = currentDate(); // get fixed current date
// difference of dates
var difference = current_date - target_date;
// if difference is negative than it's pass the target date
if (difference > 0) {
// stop timer
clearInterval(interval);
if (callback && typeof callback === 'function') callback();
return;
}
// basic math variables
var _second = 1000,
_minute = _second * 60,
_hour = _minute * 60,
_day = _hour * 24;
// calculate dates
var days = Math.floor(difference / _day),
hours = Math.floor((difference % _day) / _hour),
minutes = Math.floor((difference % _hour) / _minute),
seconds = Math.floor((difference % _minute) / _second);
// fix dates so that it will show two digets
days = (String(days).length >= 2) ? days : '0' + days;
hours = (String(hours).length >= 2) ? hours : '0' + hours;
minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;
// set to DOM
//
};
// start
var interval = setInterval(countdown, 1000);
};
JSFiddle
var original_date = currentDate();
var target_date = new Date('12/31/2020 12:00:00'); // Count up to this date
var interval;
function resetCountdown() {
original_date = currentDate();
}
function stopCountdown() {
clearInterval(interval);
}
function countdown () {
var current_date = currentDate(); // get fixed current date
// difference of dates
var difference = current_date - original_date;
if (current_date >= target_date) {
// stop timer
clearInterval(interval);
if (callback && typeof callback === 'function') callback();
return;
}
// basic math variables
var _second = 1000,
_minute = _second * 60,
_hour = _minute * 60,
_day = _hour * 24;
// calculate dates
var days = Math.floor(difference / _day),
hours = Math.floor((difference % _day) / _hour),
minutes = Math.floor((difference % _hour) / _minute),
seconds = Math.floor((difference % _minute) / _second);
// fix dates so that it will show two digets
days = (String(days).length >= 2) ? days : '0' + days;
hours = (String(hours).length >= 2) ? hours : '0' + hours;
minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;
// set to DOM
//
};
// start
interval = setInterval(countdown, 1000);
};
This OP already has an answer but that has issue with timezone , so this answer.
DownVoters care to comment.
Try this. Fiddle
var TargetDate = new Date('2015', '08', '04', 11, 11, 30) // second parameter is month and it is from from 0-11
$('#spanTargetDate').text(TargetDate);
$('#spanStartDate').text(new Date());
var Sec = 0,
Min = 0,
Hour = 0,
Days = 0;
var counter = setInterval(function () {
var CurrentDate = new Date()
$('#spanCurrentDate').text(CurrentDate);
var Diff = TargetDate - CurrentDate;
if (Diff < 0) {
clearInterval(counter);
$('#timer').text('Target Time Expired. test in fiddle')
} else {
++Sec;
if (Sec == 59) {
++Min;
Sec = 0;
}
if (Min == 59) {
++Hour;
Min = 0;
}
if (Hour == 24) {
++Days;
Hour = 0;
}
if (Sec <= Diff) $('#timer').text(pad(Days) + " : " + pad(Hour) + " : " + pad(Min) + " : " + pad(Sec));
}
}, 1000);
function pad(number) {
if (number <= 9) {
number = ("0" + number).slice(-4);
}
return number;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Target Time - <span id="spanTargetDate"></span>
<br/>
<br/>Start Time - <span id="spanStartDate"></span>
<br/>
<br/>Current Time - <span id="spanCurrentDate"></span>
<br/>
<br/>Timer (DD:HH:MM:SS) - <span id="timer"></span>
<br/>
<br/>

JavaScript incorrect time showing between two time

I have tried to show time between two time while page load.
Please check below my code -
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
function hourDiff(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);
return (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes;
//setTimeout(function(){hourDiff(start, end)},500);
}
document.getElementById("diff").value = hourDiff(start, end);
<input id="start" value="20:00"> <!-- 08.00 PM -->
<input id="end" value="09:30"> <!-- 09.30 AM -->
<input id="diff">
I have used start time 20.00 and end time 09.30 the different between two time is = 13.30 hours but it is showing wrong hour. Please check and let me know.
Edit:
Also I want to the how many hour:minute:second left
If your dates are always in the same format hh:mm, why don't you try my suggestion.
It is quite simple:
var hours = end[0] - start[0];
if(start[0] > end[0]) {
hours = 24 + hours;
}
var minutes = end[1] - start[1];
if(start[1] > end[1]) {
minutes = 60 + minutes;
if(hours == 0) {
hours = 23;
} else {
hours--;
}
}
I just substract them each other and react if the start value is bigger than the end value.
Fiddle: https://jsfiddle.net/rvwr9h0w/1/
Edit
I found a simpler solution, because of Shotgun Ninja's post:
https://jsfiddle.net/rvwr9h0w/4/
var endDate = new Date(0, 0, (start > end)?1:0 , end[0], end[1], end[2]);
If the start time is bigger than the end time, just set the end date 1 day ahead.
Okay, the problem with your code here is that you're subtracting an earlier time from a later time, which results in a negative time difference. I think what you meant to do was to have the system subtract 9:30am the next day from 8:00pm the previous day, but you've supplied no information that would indicate that they are separate days.
You have:
var startDate = new Date(0, 0, 0, 20, 0, 0); // 8:00pm, Dec 31st, 1899 (current TZ)
var endDate = new Date(0, 0, 0, 9, 30, 0); // 9:30am, Dec 31st, 1899 (current TZ)
(Year = 0 corresponds to 1900, Month = 0 corresponds to January, and Day = 0 corresponds to 1 day before the 1st, which rolls back to Dec 31.)
The important part here is that by setting all values to 0, you're getting the same day, but a different hour. So you're actually getting a negative value in the diff; the code functions correctly, but is giving you a negative hour value because the dates are out of order.
Try using Math.floor with the whole math equation required for each part:
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
function hourDiff(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 msec = diff;
var hh = Math.floor(msec / 1000 / 60 / 60);
msec -= hh * 1000 * 60 * 60;
var mm = Math.floor(msec / 1000 / 60);
return hh + ":" + mm;
//setTimeout(function(){hourDiff(start, end)},500);
}
document.getElementById("diff").value = hourDiff(start, end);
<input id="start" value="20:00"> <!-- 08.00 PM -->
<input id="end" value="09:30"> <!-- 09.30 AM -->
<input id="diff">

getting trouble in calculating time difference

this is my javascript code to calculate time difference:
var startTime = '11:30 am';
var EndTime = '1:30 pm';
var ed = EndTime.split(':');
var st = startTime.split(':');
var sub = parseInt(ed[0]) * 60 + parseInt(ed[1]);
var sub1 = parseInt(st[0]) * 60 + parseInt(st[1]);
i am getting outout:-600
i want difference in output as:2 hour.
can anybody figure out whats wrong with my code??
I would suggest
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);
return (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes;
}
Check this fiddle
http://jsfiddle.net/shubhambhave/D9M8a/
Please, use more your mind.
First, you're not even looking at the AM or PM.
If you are sure your times will look like this (and not timestamp or anything else), you can do this (I try to keep your logic here):
var startTime = '11:30 am';
var endTime = '1:30 pm';
var st = startTime.split(':');
var ed = endTime.split(':');
if ((st[1].split(' '))[1] == 'pm')
st[0] = parseInt(st[0]) + 12;
if ((ed[1].split(' '))[1] == 'pm')
ed[0] = parseInt(ed[0]) + 12;
st[1] = (st[1].split(' '))[0];
ed[1] = (ed[1].split(' '))[0];
var diff = ((ed[0] * 60 + ed[1] * 60) - (st[0] * 60 + st[1] * 60)) / 60;
In fact, you forgot to remove the 'am' part of the time.
You also forget to calculate it.
This code can be refactored, but i'm not gonna do all the job.

Get Sum of Javascript Date function

I have code for get time difference form two time
var starthours = document.getElementById("time3").value;
var endhours = document.getElementById("time4").value;
start = starthours.split(".");
end = endhours.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);
document.getElementById("hourdiff").value = (hours < 9 ? "0" : "") + hours + "." + (minutes < 9 ? "0" : "") + minutes;
But now I have to add another time field for this results, I get that value using this code
var timetv = document.getElementById("timetv").value;
And I want to add this to above time difference how to do that, Please help me..
Start time = 10.30
End time = 12.30
Time TV = 01.15
Resualt = (End Time - Start time) + Time TV
And answer should be = 3.15
Try This,
var starthours = document.getElementById("time3").value;
var endhours = document.getElementById("time4").value;
var timetv = document.getElementById("timetv").value;
start = starthours.split(".");
end = endhours.split(".");
tvtime = timetv.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);
hours = hours + parseInt(tvtime[0]);
minutes = minutes + parseInt(tvtime[1]);
this one is for getting the value when you already have the dates parsed into Date object from your form.
http://jsfiddle.net/gLReS/
var time1 = new Date('2013/08/12 10:30');
var time2 = new Date('2013/08/12 12:30');
var time3 = new Date('2013/08/12 1:15');
var result = (time2.getTime() - time1.getTime()) + time3.getTime();
var resultTime = new Date(result);
alert(resultTime);
The other thing is however getting these objects, and this one depends on your date format.
I don't understand, what is your problem.
var d = new Date(
new Date(0, 0, 0, 12, 30) -
new Date(0, 0, 0, 10, 30) +
(+new Date(0, 0, 0, 1, 15)) // transform Date into timestamp
);
[d.getHours(), d.getMinutes()]; // [3, 15]
Also, I usually replace
(hours < 9 ? "0" : "") + hours
with
("0" + hours).slice(-2)

Categories