tino tino - 6 months ago 11
Javascript Question

sum two dates in node.js return?

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