tino tino - 6 months ago 17
Node.js Question

sum two dates in node.js?

i'm trying to sum two dates.

date1 and date2 are Date() objects.

i read oher questions and googled it.. i tryed this way but it return a negative number

var sum_millis = date1.getTime()+date2.getTime();

var sum=new Date(sum_millis);

console.log(sum.toString());


date1: 1901-02-01T00:10:00.000Z

date2: 1901-01-31T23:07:23.000Z

result: -4349551357000

what i'm doing wrong?

Answer

You should substract zero-date from each date to manipulate with time.

var t0 = Date(0,0,0)).getTime();
var t1 = (new Date(0, 0, 0, 0, 0, 15)).getTime() - t0; // 15000 ms
var t2 = (new Date(0, 0, 0, 0, 0, 30)).getTime() - t0; // 30000 ms
var sum = t1 + t2; // 45000ms

You can use something like moment.js to simplify things like this:

var sum = moment()
  .hour('12').minute('44')
  .add(4,'hours').add(20, 'minutes')
  .format("HH:mm");

Or implement it:

// Convert a time in hh:mm format to minutes
function timeToMins(time) {
  var b = time.split(':');
  return b[0]*60 + +b[1];
}

// Convert minutes to a time in format hh:mm
// Returned value is in range 00  to 24 hrs
function timeFromMins(mins) {
  function z(n){return (n<10? '0':'') + n;}
  var h = (mins/60 |0) % 24;
  var m = mins % 60;
  return z(h) + ':' + z(m);
}

// Add two times in hh:mm format
function addTimes(t0, t1) {
  return timeFromMins(timeToMins(t0) + timeToMins(t1));
}

console.log(addTimes('12:13', '01:42')); // 13:55
console.log(addTimes('12:13', '13:42')); // 01:55
console.log(addTimes('02:43', '03:42')); // 06:25