-3

I have a date like this 2017-07-25 09:30:49, when I subtract 2017-07-25 10:30:00 and 2017-07-25 09:30:00, I need a result like 1 Hours.

I can't find correct search key for googling what I need. Anyone know what should I search on google ? or someone knows some function about that?

PS. Mysql or Javascript

Sibiraj
  • 4,486
  • 7
  • 33
  • 57

5 Answers5

1

Try with date object in javascript
Like this

var d1 = new Date("2017-07-25 10:30:00"); 
var d2 = new Date("2017-07-25 09:30:49") 
var diff = Math.abs(d1-d2);  // difference in milliseconds

Then convert the milliseconds to hours

var hours = parseInt((diff/(1000*60*60))%24);
Bibhudatta Sahoo
  • 4,808
  • 2
  • 27
  • 51
1

You can go through it Get the time difference between two datetimes

But the query is not clear do you want only the hour difference or you want the difference converted to hour format

Like what it will give if 2017-07-25 09:30:49 and 2017-07-26 10:30:00 ? 25 hour or 1 hour?

kakon
  • 701
  • 6
  • 18
1

here a code example of how to do it

var date1 = new Date("2017-07-25 09:30:49"); 
var date2 = new Date("2017-07-25 10:30:00");

var datesum = new Date(date1 - date2);
var hours = datesum.getHours();
var minutes = datesum.getMinutes();
var seconds = datesum.getSeconds();

console.log(hours + " hour, " + minutes + " minutes, " + seconds + " seconds" )
Ram Segev
  • 2,563
  • 2
  • 12
  • 24
0
var dateString = "2017-07-25 09:30:49";
var dateString2= "2017-07-25 11:30:00";
var reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
var dateArray = reggie.exec(dateString); 
var dateArray2= reggie.exec(dateString2); 
var dateObject1= new Date(
(+dateArray[1]),
(+dateArray[2])-1, // Careful, month starts at 0!
(+dateArray[3]),
(+dateArray[4]),
(+dateArray[5]),
(+dateArray[6])
);
var dateObject2= new Date(
(+dateArray2[1]),
(+dateArray2[2])-1, // Careful, month starts at 0!
(+dateArray2[3]),
(+dateArray2[4]),
(+dateArray2[5]),
(+dateArray2[6])
);
var diff = Math.abs(dateObject2-dateObject1);  // difference in milliseconds
 var hours = parseInt((diff/(1000*60*60))%24);
Osama
  • 2,912
  • 1
  • 12
  • 15
0

Try with the below dateFormatter function :

var d1 = new Date("2017-07-25 10:30:00"); 
var d2 = new Date("2017-07-25 09:30:00") 
var diff = Math.abs(d1-d2);
var d = dateFormatter(diff);
console.log(d);

function dateFormatter(t){
    var cd = 24 * 60 * 60 * 1000;
    var ch = 60 * 60 * 1000;
    var cm = 60*1000;
    var d = Math.floor(t / cd);
    var h = '0' + Math.floor( (t - d * cd) / ch);
    var m = '0' + Math.round( (t - d * cd - h * ch) / 60000);
    var s = '0' + Math.round((t - (d * cd) - (h * ch) - (m * cm))/1000);
    return d + " days, " + h.substr(-2) + " hours, " + m.substr(-2) + " minutes, " +s.substr(-2)+ " seconds";
}
Nik
  • 173
  • 2
  • 17