Time difference and summation between multiple rows on change - javascript

I am trying to write a code that can do the following :
Calculates time difference (in HH:MM format) between two type="time" elements on a row.
Sum the total difference (in HH:MM format) in text input.
I've managed to create a function fired by the onchange event, but my function is only considering the first values entered, meaning that when you update the timings, the difference will be recalculated and the total will be wrong.
Here is my JavaScript code for calculating the first line:
function CalTime0() {
var timeOfCall = $('#timefrom0').val(),
timeOfResponse = $('#timeto0').val(),
hours = timeOfResponse.split(':')[0] - timeOfCall.split(':')[0],
minutes = timeOfResponse.split(':')[1] - timeOfCall.split(':')[1],
total = $('#tbtotal').val(),
tothours = total.split(':')[0],
totminutes = total.split(':')[1];
minutes = minutes.toString().length<2?'0'+minutes:minutes;
totminutes = totminutes.toString().length<2?'0'+totminutes:totminutes;
if(minutes<0) {
hours--;
minutes = 60 + minutes;
}
hours = hours.toString().length<2?'0'+hours:hours;
tothours = tothours.toString().length<2?'0'+tothours:tothours;
tothours = parseInt(tothours) + parseInt(hours);
totminutes = parseInt(totminutes) + parseInt(minutes);
if(totminutes >= 60) {
tothours++;
totminutes = totminutes - 60;
}
$('#total0').val(hours + ':' + minutes);
$('#tbtotal').val(tothours + ':' + totminutes);
}

The solution is to substract the time the #total0 field represents from the time the #tbtotal field represents. Then you calculate the new #total0 field, and add that time to #tbtotal again. This way the time displayed in #tbtotal is always correct.
The other question seemed to be how to do this for all rows, instead of just this one. You can use the this keyword to figure out what element fired the change event. From there you can figure out what the other elements would be. For this purpose I renamed the fields to timefr0 and timeto0, so they are equal length.
I took the liberty to convert all times to seconds, and manipulate them that way. The comments in the script should speak for themselfs.
function updateTotals() {
//Get num part of the id from current set
//Cheated a bit with the id names ;-)
var num = $(this).attr('id').substr( 6 );
//Get the time from each and every one of them
var tfrom = $('#timefr' + num ).val().split(':');
var tto = $('#timeto' + num ).val().split(':');
var currtotal = $('#total' + num ).val().split(':');
var grandtotal = $('#tbtotal').val().split(':');
//Convert to seconds and do the calculations the easy way
var diff = (tto[0] - tfrom[0]) * 3600 + (tto[1] - tfrom[1]) * 60;
var totalsec = currtotal[0] * 3600 + currtotal[1] * 60;
var grandtotalsec = grandtotal[0] * 3600 + grandtotal[1] * 60;
//If the result is negative, we can't do anything sensible. Use 0 instead.
if( diff < 0 ) {
diff = 0;
}
//Substract what we calculated last time
grandtotalsec -= totalsec;
//Then add the current diff
grandtotalsec += diff;
//Convert diff (or total) into human readable form
var hours = Math.floor( diff / 3600 );
diff = diff % 3600;
var minutes = Math.floor( diff / 60 );
hours = (hours < 10) ? "0" + hours.toString() : hours.toString();
minutes = (minutes < 10) ? "0" + minutes.toString() : minutes.toString();
//Convert grandtotal into human readable form
var grandtotalhours = Math.floor( grandtotalsec / 3600 );
grandtotalsec = grandtotalsec % 3600;
var grandtotalminutes = Math.floor( grandtotalsec / 60 );
grandtotalhours = (grandtotalhours < 10) ? "0" + grandtotalhours.toString() : grandtotalhours.toString();
grandtotalminutes = (grandtotalminutes < 10) ? "0" + grandtotalminutes.toString() : grandtotalminutes.toString();
//Put them in the fields
$( '#total' + num ).val( hours + ":" + minutes );
$( '#tbtotal' ).val( grandtotalhours + ":" + grandtotalminutes );
}
An example fiddle can be found here.

As a suggestion, to compute date differences more easily, use moment.js. The date difference computation should be replaceable by something like this, with moment:
moment(timeOfResponse).diff(moment(timeOfCall))
moment.js diff documentation: http://momentjs.com/docs/#/displaying/difference/

Related

Difference between two times (not dates) in format (hh:mm)

For example I have these two times as string:
Time_A = "07:35" (means 7 hours and 35 minutes)
Time_B = "15:00" (means 15 hours and 00 minutes)
Now I would like to substract the Time_B from Time_A. This should return "-07:25" (means minus 7 hours and 25 minutes) Therefore I tried using the following function:
function time_diff(Time_A,Time_B ) {
var t1parts = t1.split(':');
var t1cm = Number(t1parts[0]) * 60 + Number(t1parts[1]);
var t2parts = t2.split(':');
var t2cm = Number(t2parts[0]) * 60 + Number(t2parts[1]);
var hour = Math.floor((t1cm - t2cm) / 60);
var min = Math.floor((t1cm - t2cm) % 60);
return (hour + ':' + min + ':00');
}
But this function is returning: -8:-25:00 instead of -07:25:00. Any idea how to fix this?
It's because you are rounding a negative number down:
Math.floor(-455/60) = Math.floor(-7.4166667) = -8
You could do:
var diff = Math.abs(t1cm - t2cm);
var hour = Math.floor(diff / 60);
var min = diff % 60;
return (t1cm < t2cm ? '-' : '') + hour + ':' + min + ':00';

Converting Float to Time in Javascript

I am having a three String or Float values say 9.30, 8.00 and 0.40 as Total_hour, Paid_hour, Extra_hour
These should be actually 9 hours 30 minutes, 8 hours 0 minutes, 0 hours 40 minutes.
Question 1) How to convert 9.30 to 9 hours 30 minutes
Question 2) Later want to Subtract and get Remaining Hour = Total_hour-Paid_Hour-Extra_hour
Later the answer Remaining Hour should be in float
This should work.
You just need to convert to ms:
let timefloat = 9.3;
function convertToMs(timefloat) {
// Get the minutes portion
let remainder = timefloat % 1;
// Convert into ms
let minutes = remainder * 100 * 60 * 1000;
// Get the number of hours and convert to ms
let hours = (timefloat - remainder) * 60 * 60 * 1000;
return minutes + hours;
}
// Convert back to float format
function convertToFloat(date) {
let hours = date.getUTCHours();
let mins = date.getUTCMinutes();
return hours + (mins / 100);
}
// Log the result
console.log(new Date(convertToMs(9.3)).toUTCString());
console.log(new Date(convertToMs(8.0)).toUTCString());
console.log(new Date(convertToMs(9.3) - convertToMs(8.0)).toUTCString());
let diff = convertToMs(9.3) - convertToMs(8.0);
console.log(convertToFloat(new Date(diff)))
The following javascript snippet converts a given float to hours and minutes. Source float to time
function convertNumToTime(number) {
// Check sign of given number
var sign = (number >= 0) ? 1 : -1;
// Set positive value of number of sign negative
number = number * sign;
// Separate the int from the decimal part
var hour = Math.floor(number);
var decpart = number - hour;
var min = 1 / 60;
// Round to nearest minute
decpart = min * Math.round(decpart / min);
var minute = Math.floor(decpart * 60) + '';
// Add padding if need
if (minute.length < 2) {
minute = '0' + minute;
}
// Add Sign in final result
sign = sign == 1 ? '' : '-';
// Concate hours and minutes
time = sign + hour + ':' + minute;
return time;
}
console.log(convertNumToTime(11.15));
Output
11:09
First convert the number in minutes and then do your subtraction. Then convert your output to hours.
var Total_hour = '9.30',
Paid_hour = '8.00',
Extra_hour = '0.40';
var conversionInMinutes = hour => Math.floor(hour) * 60 + (hour - (Math.floor(hour))) * 100;
var conversionInHours = min => Math.floor( min/60 ) + min % 60 / 100;
var Remaining_hour = conversionInMinutes(Total_hour) - conversionInMinutes(Paid_hour) - conversionInMinutes(Extra_hour);
console.log(conversionInHours(Remaining_hour).toFixed(2));
function doTime(input)
{
input = input.toString()
inputs = input.split(".")
return (inputs[0] + "Hour and" + inputs[1] + "minutes")
}
doTime("9:22")
function substract2
function subtract2(a , b){
a = input.toString()
arrayA = input.split(".")
b = input.toString()
arrayB = input.split(".")
h = parseInt(arrayB[0]) - parseInt(arrayA[0])
h <0 ? h+=12/*or 24*/ :h=h
m = parseInt(arrayB[1]) - parseInt(arrayA[1])
if(m<0){h-- ; m+=60}
return h.toString() + ":" + m.toString()
}

Counting down seconds from 1970 time in javascript

I am using an API that returns the time like this deal_expiration_time:1469396377 which looks like its seconds from 1970. I am trying to get a countdown in MM/SS This is in angular so I apparently can't use jQuery? I have struggled for a while and am stumped with this code. I'm trying to make it so its input: 1469396377 | output: 08:21
function(){
var x1, secs1 = 510;
x1 = setInterval(function(){myFunc1(9)}, 1000);
function myFunc1(timerId){
var minutes = Math.floor(secs1 / 60);
var seconds = secs1 % 60;
$('#timer_'+timerId).html(minutes + ':' + seconds); //assuming there is a label with Id 'timer'
secs1--;
if(secs1 == 0){
document.getElementById('timer_' + timerId).style.hidden = true;
clearInterval(x1);
}
}
}
You can get the current time using Date.now() and then manually calculate the difference in time. This function gets the difference between the given time and the current time, calculates the difference in seconds and in minutes. This difference is then formatted as a countdown string and then returned.
function getTimeDifference(expirationTime) {
var now = Date.now();
var diff = expirationTime - now;
var secDiff = Math.round(diff/1000);
var minDiff = Math.round(secDiff / 60);
var diffStr = minDiff + ":" + (secDiff - minDiff * 60);
return diffStr
}

Moment.js adding difference between multiple dates

I am using the following code to get difference between two dates in hrs, minutes and seconds, which I will save later in database as a string field. So I was wondering if it is possible to use Moment.js library or any Javascript functionally in order to get the total number of hours, minutes and seconds for all date differences saved in the database (ex. 02:24:33 + 03:12:20 + 12:33:33) as one final HH:MM:SS taking in consideration that the HH could exceed 24 if the total number of hours summed exceeded 24? Thanks
$('.set-start-time').on("dp.change",function (e) {
$('.set-end-time').data("DateTimePicker").setMinDate(e.date);
});
$('.set-end-time').on("dp.change",function (e) {
$('.set-start-time').data("DateTimePicker").setMaxDate(e.date);
var now = $('.set-start-time').data('DateTimePicker').getDate().toLocaleString();
var then = $('.set-end-time').data('DateTimePicker').getDate().toLocaleString();
console.log(moment.utc(moment(then,"DD/MM/YYYY HH:mm:ss").diff(moment(now,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss"));
//Output here come in format ex. 02:42:33
});
It's probably too late for this to matter, but maybe something like this would help:
http://jsfiddle.net/8s8v3evf/8/
tl;dr
once you have your diff:
function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
function diffAsString(diff_ms) {
var hours = Math.floor(diff_ms / 3600000);
diff_ms -= (hours * 3600000);
var minutes = Math.floor(diff_ms / 60000);
diff_ms -= (minutes * 60000);
var seconds = Math.floor(diff_ms / 1000);
return zeroPad(hours, 2) + ':' + zeroPad(minutes, 2) + ':' + zeroPad(seconds, 2);
}

String to date conversion not working correctly in Javascript

I need to get time difference in this format: "HH:MM:SS" using a Javascript.
I have tried this:
var diff = Date.parse( time2) - Date.parse( time1 );
var total_time = (diff / 1000 / 60 / 60) + ":" + (diff / 1000 / 60) + ":" + (diff / 1000);
and this:
var diff = new Date( time2) - new Date( time1 );
var total_time = (diff / 1000 / 60 / 60) + ":" + (diff / 1000 / 60) + ":" + (diff / 1000);
These are the values of time2 and time1:
time1: "2012-11-07 15:20:32.161"
time2: "2012-11-07 17:55:41.451"
And result I am getting in both cases is:
total_time= 0.5250819444444444:31.504916666666666:1890.295
Which you can see is not correct
I think you are getting wrong diff value because of the millisecond part in the date delimited by .. Its not being accepted correctly by the data parser.
Try using the date and time part excluding the milliseconds as below:
var diff = Date.parse(time2.split(".")[0]) - Date.parse( time1.split(".")[0]);
Also while you are getting wrong difference diff, your time computation is also wrong.
It should be:
var second = Math.floor(diff /1000);
//convert the seconds into minutes and remainder is updated seconds value
var minute = Math.floor(second /60);
second = second % 60;
//convert the minutes into hours and remainder is updated minutes value
var hour = Math.floor(minute/60);
minute = minute %60;
var total_time= hour+":" minute+":"+second;
You forgot to remove the number of milliseconds you already calculated from diff. Here is a very verbose example on how you do it in a propper way.
var time1 = "2012-11-07 15:20:32.161",
time2 = "2012-11-07 17:55:41.451",
SECOND = 1000,
MINUTE = SECOND* 60,
HOUR = MINUTE* 60;
var diff = new Date(time2) - new Date(time1);
var hours = Math.floor(diff / HOUR); // Calculate how many times a full hour fits into diff
diff = diff - (hours * HOUR); // Remove hours from difference, we already caluclated those
var minutes = Math.floor(diff / MINUTE); // Calculate how many times a full minute fits into diff
diff = diff - (minutes * MINUTE); // Remove minutes from difference
var seconds = Math.floor(diff / SECOND); // As before
diff = diff - (seconds * SECOND);
var rest = diff;
var total_time = hours + ":" + minutes + ":" + seconds + " " + rest ;
DEMO

Categories

Resources