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?
var datetime = new Date(date.getFullYear(), date.getMonth(), date.getDate(),
time.getHours(), time.getMinutes(), time.getSeconds());
How about something like this:
var year = date.getFullYear(),
month = date.getMonth(),
day = date.getDate();
time.setFullYear(year);
time.setMonth(month);
time.setDate(day);
var parts = ['Hours', 'Minutes', 'Seconds', 'Milliseconds'];
for (var i=0, p; p=parts[i], i<parts.length; i++) {
date['setUTC'+p]( time['getUTC'+p]() );
}
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With