Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge two dates in JavaScript?

I have 2 date objects. I want to take the date from one and the time from the other and combine them into a new date object.

date.toString() = Wed Dec 21 2011 00:00:00 GMT+0000 (GMT)
time.toString() = Sun Dec 31 2000 03:00:00 GMT+0000 (GMT)

# I want to end up with
datetime.toString() = Wed Dec 21 2011 03:00:00 GMT+0000 (GMT)

How can I best accomplish this?

like image 444
David Tuite Avatar asked Dec 07 '11 23:12

David Tuite


5 Answers

var datetime = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 
                        time.getHours(), time.getMinutes(), time.getSeconds());
like image 62
pna Avatar answered Nov 17 '22 11:11

pna


How about something like this:

var year  = date.getFullYear(),
    month = date.getMonth(),
    day   = date.getDate();

time.setFullYear(year);
time.setMonth(month);
time.setDate(day);
like image 25
Tikhon Jelvis Avatar answered Nov 17 '22 10:11

Tikhon Jelvis


var parts = ['Hours', 'Minutes', 'Seconds', 'Milliseconds'];
for (var i=0, p; p=parts[i], i<parts.length; i++) {
  date['setUTC'+p]( time['getUTC'+p]() );
}
like image 3
Tomalak Avatar answered Nov 17 '22 09:11

Tomalak


you can use string functions to build the target string...

datetime = date.toString().substr(0,16) + time.toString().substr(16,40)

then if you need to have it as a date object, feed it into a new date()

like image 2
Billy Moon Avatar answered Nov 17 '22 10:11

Billy Moon


var msPerDay = 1000 * 60 * 60 * 24;
var newDateTime = new Date(date.getTime() + (time.getTime() % msPerDay));

EDIT: mine assumes date variable is a date without any time.

like image 1
Daniel Moses Avatar answered Nov 17 '22 09:11

Daniel Moses