Get Sum of Javascript Date function - javascript

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)

Related

Difference between two html time inputs

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

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.

Determine minutes until midnight

How would you go about determining how many minutes until midnight of the current day using javascript?
function minutesUntilMidnight() {
var midnight = new Date();
midnight.setHours( 24 );
midnight.setMinutes( 0 );
midnight.setSeconds( 0 );
midnight.setMilliseconds( 0 );
return ( midnight.getTime() - new Date().getTime() ) / 1000 / 60;
}
Perhaps:
function minsToMidnight() {
var now = new Date();
var then = new Date(now);
then.setHours(24, 0, 0, 0);
return (then - now) / 6e4;
}
console.log(minsToMidnight());
or
function minsToMidnight() {
var msd = 8.64e7;
var now = new Date();
return (msd - (now - now.getTimezoneOffset() * 6e4) % msd) / 6e4;
}
console.log(minsToMidnight())
and there is:
function minsToMidnight(){
var d = new Date();
return (-d + d.setHours(24,0,0,0))/6e4;
}
console.log(minsToMidnight());
or even a one-liner:
minsToMidnight = () => (-(d = new Date()) + d.setHours(24,0,0,0))/6e4;
console.log(minsToMidnight());
You can get the current timestamp, set the hours to 24,
and subtract the old timestamp from the new one.
function beforeMidnight(){
var mid= new Date(),
ts= mid.getTime();
mid.setHours(24, 0, 0, 0);
return Math.floor((mid - ts)/60000);
}
alert(beforeMidnight()+ ' minutes until midnight')
Here's a one-liner to get milliseconds until midnight
new Date().setHours(24,0,0,0) - Date.now()
And for the minutes until midnight, we divide that by 60 and then by 1000
(new Date().setHours(24,0,0,0) - Date.now()) / 60 / 1000
Posting this as an alternative solution which works for any hour of the day.
const timeUntilHour = (hour) => {
if (hour < 0 || hour > 24) throw new Error("Invalid hour format!");
const now = new Date();
const target = new Date(now);
if (now.getHours() >= hour)
target.setDate(now.getDate() + 1);
target.setHours(hour);
target.setMinutes(0);
target.setSeconds(0);
target.setMilliseconds(0);
return target.getTime() - now.getTime();
}
const millisecondsUntilMidnight = timeUntilHour(24);
const minutesUntilMidnight = millisecondsUntilMidnight / (60 * 1000);

Leading zero when subtracting one time from another javascript

function setValue() {
var startTime = document.getElementById('ToilA');
var endTime = document.getElementById('EndHours'); startTime = startTime.value.split(":");
var startHour = parseInt(startTime[0], 10);
var startMinutes = parseInt(startTime[1], 10);
endTime = endTime.value.split(":");
var endHour = parseInt(endTime[0], 10);
var endMinutes = parseInt(endTime[1], 10);
//var hours, minutes;
var today = new Date();
var time1 = new Date(2000, 01, 01, startHour, startMinutes, 0);
var time2 = new Date(2000, 01, 01, endHour, endMinutes, 0); var milliSecs = (time2 - time1);
msSecs = (1000);
msMins = (msSecs * 60);
msHours = (msMins * 60);
numHours = Math.floor(milliSecs/msHours);
numMins = Math.floor((milliSecs - (numHours * msHours)) / msMins);
numSecs = Math.floor((milliSecs - (numHours * msHours) - (numMins * msMins))/ msSecs); numSecs = "0" + numSecs;
numMins = "0" + numMins;
DateCalc = (numHours + ":" + numMins);
document.getElementById('CalculateHours').value = DateCalc; }
I have one more issue with this code, there is a leading 0 when the minute part is over 10.
so it return something like 11:013 rather that 11:13, can this be fixed with math or will an if statement fix this? Like if number of items > 2, remove first item?
I was going to just do a PHP script to remove this when the form is submitted, but it doesn't look good.
Change numMins = "0" + numMins to
if (numMins < 10)
numMins = "0" + numMins;
if (numSecs < 10)
numSecs = "0" + numSecs;
if (numMins < 10)
numMins = "0" + numMins;

Categories