简体   繁体   中英

How do I subtract hour in javascript?

I get the result below.

data[11] = "12:05:00";
data[10] = "02:00:00";

I want to subtract date[11] and date[10] so it will return '10 hours 5 minutes' value to my other variable and using javascript.

So far, I've tried this code:

function getAct(data, s) {

  var startTime = data[10];
  var endTime = data[11];

  var s = startTime.split(':');
  var e = endTime.split(':');

  var end = new Date(0, 0, 0, parseInt(e[1], 10), parseInt(e[0], 10), 0);
  var start = new Date(0, 0, 0, parseInt(s[1], 10), parseInt(s[0], 10), 0);

  var elapsedMs = end - start;
  var elapsedMinutes = elapsedMs / 1000 / 60;

  return elapsedMinutes;

}

I get only minutes from the result and the result is incorrect.

1) well... you code is simply wrong. put start and end int he middle of the method to the console.log and see what you are doing.

So, to start with your code you need to change:

var end = new Date(0, 0, 0, parseInt(e[1], 10), parseInt(e[0], 10), 0);
var start = new Date(0, 0, 0, parseInt(s[1], 10), parseInt(s[0], 10), 0);

to:

var end = new Date(0, 0, 0, parseInt(e[0], 10), parseInt(e[1], 10), 0);
var start = new Date(0, 0, 0, parseInt(s[0], 10), parseInt(s[1], 10), 0);

Then your method should return minutes correctly for most of the time. Then you can convert it to hours and minutes by yourself.

2) However, you have to keep in mind, that there are also DST changes when applies to date/time. So, I highly recommed to use some library like http://momentjs.com/ to handle manipulations with time.

Try Like this. It returns Correct minutes:

 function getAct(data, s) { var startTime = data[10]; var endTime = data[11]; var s = startTime.split(':'); var e = endTime.split(':'); var end = parseInt(e[0])* 60+ parseInt(e[1]); var start = parseInt(s[0])*60 + parseInt(s[1]); var elapsedMs = end - start; return elapsedMs ; } var data=[]; data[11] = "12:05:00"; data[10] = "02:00:00"; var minutes=getAct(data); var hours=parseInt(minutes/60)+" hours "+ minutes%60 +" minutes"; 

This is dirty, but this is another way

 var startTime = "02:00:00"; var endTime = "12:05:00"; var dummyDate = "1/1/2000"; var timeDiff = (new Date(dummyDate + " " + endTime)).getTime() - (new Date(dummyDate + " " + startTime)).getTime(); var seconds = ~~(timeDiff/1000); var hour = ~~(seconds/60/60); var min = ~~((seconds - 60*60*hour) / 60); seconds = ~~(((seconds - 60*60*hour) - min*60)); console.log(hour+":"+min+":"+seconds); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM