jackhammer013 jackhammer013 - 6 months ago 25
Javascript Question

Subtract and Add timestamps jquery

I know there is alot of things like this in stackoverflow but I can't seem to find something similar to mine.

I have datatable which has columns

start_timestamp
and
end_timestamp
and
total_hours
. I am using this in a task management to calculate how much time you spend in a task. So basically to get the
total_hours
in a task you need to subtract
end_timestamp
and
start_timestamp
but I am only able to get the hours. My timestamp format is like
Y-m-d h:i:s
2016-05-04 23:00:00. Problem is I also need to get the minutes. Plus in the end I need to add all the hours for all the tasks. My current code is:

var totalhours = 0;
$.each(myObj[0], function(key,value) {

var date_start = new Date(value.start_timestamp);
var date_end = new Date(value.end_timestamp);
var milisec = Math.abs(date_end - date_start);
var seconds = milisec / 1000;
var hours = parseInt( seconds / 3600 );

totalhours += hours;

var isdaily = '';
if(value.is_daily == 0)
{
isdaily = 'Added'
}
else
{
isdaily = 'Daily'
}

t.row.add( [
value.id,
value.task_description,
value.start_timestamp,
value.end_timestamp,
hours,
value.name,
value.assign,
value.created_at,
isdaily,
value.status
] ).draw();
});


So basically
totalhours
is total hours for all the tasks and
hours
the hours per task, how I also include the minutes?

Answer

Problem is I also need to get the minutes.

You need to add

var minutes = parseInt( seconds / 60 );

to

var hours = parseInt( seconds / 3600 );

Rest of the function logic needs to be manipulated accordingly.

If you want to convert 2.5 to 2 hours 30 minutes

var x = 2.5;
var hours = parseInt(x);
var minutes = ( x - parseInt(x) ) * 60;
Comments