Time difference between dates in JavaScript and MySQL

2

I have data_inicio and data_fim and want to know the difference of hours and minutes between them. The data_inicio will already be saved in the MySQL database as datetime , data_fim will pick the date when the user clicks a button. What is the best way to do this? Convert data_inicio to milliseconds, compare to data_inicio and then format the result to display in hours and minutes?

    
asked by anonymous 28.11.2016 / 14:10

2 answers

3

Javascript entente date in millisecond format. The way you thought to do it might work, convert data_inicio to milli. But I think converting from milliseconds to date is easier. To handle date in javascript, I recommend moment.js , which already has several ready-made functions. An example is diff (difference):

var a = moment(1390310146.791877);
var b = moment(1390309386.271075);
a.diff(b)//Diferença em milliseconds
a.diff(b,'seconds')//Diferença em segundos
a.diff(b,'minutes')//Diferença em minutos 
    
28.11.2016 / 14:30
2

You can use the mysql function DATEDIFF ()

SELECT DATEDIFF('2014-11-30','2014-11-29') AS DiffDate

(examples taken from W3Schools)

However, it returns the difference only in days. If you need something more accurate you can do the calculation of seconds, like this:

Query:

SELECT TIME_TO_SEC(data_inicio) data_inicio, TIME_TO_SEC(data_fim) data_fim FROM tabela WHERE data_fim IS NOT NULL;

Javascript:

var diferenca = data_fim - data_inicio;
var diferenca_dias = round(diferenca/86400);
var diferenca_horas = round((diferenca%8400) / 3600);
var diferenca_minutos = round(((diferenca%8400)%3600)/60);
var diferenca_segundos = round( (((diferenca%8400)%3600)%60)/60);
    
28.11.2016 / 14:26