JavaScript incorrect time showing between two time - javascript

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">

Related

Getting a negative number when calculating time in javascript

I'm working on a pdf form and trying to calculate hours from 2 fields. As long as the time does not go past midnight (in 24-hour format), I get the correct response. Once it goes past midnight, I get a negative number. Is there a way to add 24 hours to the returned value if it gives a negative number?
Here's what the field is being calculated as
var startTime = this.getField("SHIFT STARTRow1").value;
var endTime = this.getField("SHIFT ENDRow1").value;
this.getField("TOTAL HOURSRow1").value = timeDiff(startTime, endTime);
if ((event.value == "") || (event.value == Infinity) || isNaN(event.value)) {event.value = "";}
And here is the form javascript - timeDiff
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
So using this script, if I type in 12:30 as the start time and 01:45 as the end time, I get a return of -10.75. However, I need a return of 13.25.
I attempted to find another thread that helped me with this, but maybe I overlooked it. Any help?
Example
If end hour is less than start, add 24
function timeDiff(startTime, endTime) {
var startArr = startTime.split(":").map(Number);
var endArr = endTime.split(":").map(Number);
if (startArr[0] > endArr[0]) {
endArr[0] += 24;
}
var hours = endArr[0] + endArr[1]/60 - startArr[0] - startArr[1]/60;
return hours.toFixed(2)
}
console.log(timeDiff('23:10', '1:00'))
Is there a way to add 24 hours to the returned value if it gives a negative number?
Well, yes –
if(hours < 0) hours += 24;

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

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)

JavaScript - Get minutes between two dates

If I have two dates, how can I use JavaScript to get the difference between the two dates in minutes?
You may checkout this code:
var today = new Date();
var Christmas = new Date(today.getFullYear() + "-12-25");
var diffMs = (Christmas - today); // milliseconds between now & Christmas
var diffDays = Math.floor(diffMs / 86400000); // days
var diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
console.log(diffDays + " days, " + diffHrs + " hours, " + diffMins + " minutes until Christmas =)");
or var diffMins = Math.floor((... to discard seconds if you don't want to round minutes.
Subtracting two Date objects gives you the difference in milliseconds, e.g.:
var diff = Math.abs(new Date('2011/10/09 12:00') - new Date('2011/10/09 00:00'));
Math.abs is used to be able to use the absolute difference (so new Date('2011/10/09 00:00') - new Date('2011/10/09 12:00') gives the same result).
Dividing the result by 1000 gives you the number of seconds. Dividing that by 60 gives you the number of minutes. To round to whole minutes, use Math.floor or Math.ceil:
var minutes = Math.floor((diff/1000)/60);
In this example the result will be 720.
[edit 2022] Added a more complete demo snippet, using the aforementioned knowledge.
See also
untilXMas();
function difference2Parts(milliseconds) {
const secs = Math.floor(Math.abs(milliseconds) / 1000);
const mins = Math.floor(secs / 60);
const hours = Math.floor(mins / 60);
const days = Math.floor(hours / 24);
const millisecs = Math.floor(Math.abs(milliseconds)) % 1000;
const multiple = (term, n) => n !== 1 ? `${n} ${term}s` : `1 ${term}`;
return {
days: days,
hours: hours % 24,
hoursTotal: hours,
minutesTotal: mins,
minutes: mins % 60,
seconds: secs % 60,
secondsTotal: secs,
milliSeconds: millisecs,
get diffStr() {
return `${multiple(`day`, this.days)}, ${
multiple(`hour`, this.hours)}, ${
multiple(`minute`, this.minutes)} and ${
multiple(`second`, this.seconds)}`;
},
get diffStrMs() {
return `${this.diffStr.replace(` and`, `, `)} and ${
multiple(`millisecond`, this.milliSeconds)}`;
},
};
}
function untilXMas() {
const nextChristmas = new Date(Date.UTC(new Date().getFullYear(), 11, 25));
const report = document.querySelector(`#nextXMas`);
const diff = () => {
const diffs = difference2Parts(nextChristmas - new Date());
report.innerHTML = `Awaiting next XMas 🙂 (${
diffs.diffStrMs.replace(/(\d+)/g, a => `<b>${a}</b>`)})<br>
<br>In other words, until next XMas lasts…<br>
In minutes: <b>${diffs.minutesTotal}</b><br>In hours: <b>${
diffs.hoursTotal}</b><br>In seconds: <b>${diffs.secondsTotal}</b>`;
setTimeout(diff, 200);
};
return diff();
}
body {
font: 14px/17px normal verdana, arial;
margin: 1rem;
}
<div id="nextXMas"></div>
var startTime = new Date('2012/10/09 12:00');
var endTime = new Date('2013/10/09 12:00');
var difference = endTime.getTime() - startTime.getTime(); // This will give difference in milliseconds
var resultInMinutes = Math.round(difference / 60000);
A simple function to perform this calculation:
function getMinutesBetweenDates(startDate, endDate) {
var diff = endDate.getTime() - startDate.getTime();
return (diff / 60000);
}
That's should show the difference between the two dates in minutes. Try it in your browser:
const currDate = new Date('Tue Feb 13 2018 13:04:58 GMT+0200 (EET)')
const oldDate = new Date('Tue Feb 13 2018 12:00:58 GMT+0200 (EET)')
(currDate - oldDate) / 60000 // 64
This problem is solved easily with moment.js, like this example:
var difference = mostDate.diff(minorDate, "minutes");
The second parameter can be changed for another parameters, see the moment.js documentation.
e.g.: "days", "hours", "minutes", etc.
http://momentjs.com/docs/
The CDN for moment.js is available here:
https://cdnjs.com/libraries/moment.js
Thanks.
EDIT:
mostDate and minorDate should be a moment type.
EDIT 2:
For those who are reading my answer in 2020+, momentjs is now a legacy project.
If you are still looking for a well-known library to do this job, I would recommend date-fns.
// How many minutes are between 2 July 2014 12:07:59 and 2 July 2014 12:20:00?
var result = differenceInMinutes(
new Date(2014, 6, 2, 12, 20, 0),
new Date(2014, 6, 2, 12, 7, 59)
)
//=> 12
You can do as follows:
Get difference of dates(Difference will be in milliseconds)
Convert milliseconds into minutes i-e ms/1000/60
The Code:
let dateOne = new Date("2020-07-10");
let dateTwo = new Date("2020-07-11");
let msDifference = dateTwo - dateOne;
let minutes = Math.floor(msDifference/1000/60);
console.log("Minutes between two dates =",minutes);
For those that like to work with small numbers
const today = new Date();
const endDate = new Date(startDate.setDate(startDate.getDate() + 7));
const days = parseInt((endDate - today) / (1000 * 60 * 60 * 24));
const hours = parseInt(Math.abs(endDate - today) / (1000 * 60 * 60) % 24);
const minutes = parseInt(Math.abs(endDate.getTime() - today.getTime()) / (1000 * 60) % 60);
const seconds = parseInt(Math.abs(endDate.getTime() - today.getTime()) / (1000) % 60);
Here's some fun I had solving something similar in node.
function formatTimeDiff(date1, date2) {
return Array(3)
.fill([3600, date1.getTime() - date2.getTime()])
.map((v, i, a) => {
a[i+1] = [a[i][0]/60, ((v[1] / (v[0] * 1000)) % 1) * (v[0] * 1000)];
return `0${Math.floor(v[1] / (v[0] * 1000))}`.slice(-2);
}).join(':');
}
const millis = 1000;
const utcEnd = new Date(1541424202 * millis);
const utcStart = new Date(1541389579 * millis);
const utcDiff = formatTimeDiff(utcEnd, utcStart);
console.log(`Dates:
Start : ${utcStart}
Stop : ${utcEnd}
Elapsed : ${utcDiff}
`);
/*
Outputs:
Dates:
Start : Mon Nov 05 2018 03:46:19 GMT+0000 (UTC)
Stop : Mon Nov 05 2018 13:23:22 GMT+0000 (UTC)
Elapsed : 09:37:02
*/
You can see it in action at https://repl.it/#GioCirque/TimeSpan-Formatting
The following code worked for me,
function timeDiffCalc(dateNow,dateFuture) {
var newYear1 = new Date(dateNow);
var newYear2 = new Date(dateFuture);
var dif = (newYear2 - newYear1);
var dif = Math.round((dif/1000)/60);
console.log(dif);
}
It works easily:
var endTime = $("#ExamEndTime").val();
var startTime = $("#ExamStartTime").val();
//create date format
var timeStart = new Date("01/01/2007 " + startTime);
var timeEnd = new Date("01/01/2007 " + endTime);
var msInMinute = 60 * 1000;
var difference = Math.round(Math.abs(timeEnd - timeStart) / msInMinute);
$("#txtCalculate").val(difference);
this will work
duration = moment.duration(moment(end_time).diff(moment(start_time)))

Categories