Time difference between Javascript and Mysql dates

Asked

Viewed 637 times

2

Have data_inicio and data_fim and I 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 of the moment the user clicks on a button. What is the best way to do this? Convert data_inicio in milliseconds, compare to data_inicio and then format the result to display in hours and minutes?

2 answers

3


Javascript entente data in millisecond format. The way you thought about doing it might work, convert the data_inicio in Mili. But I think that converting from milliseconds to date is easier. To deal with date in javascript, recommend Moment.js, which already has several functions ready. 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 
  • I will use Moment.js. So I can compare dates in the database format in javascript without conversion, for example 2016-11-28 13:00:00? Thank you

  • 1

    Yes you can. In the documentation itself there are some examples.

  • Very good, but you will load your site with an extra plugin that you don’t need... But the decision is yours.

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 seconds calculation, this way:

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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.