Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I combine the date from one variable with the times of another with MomentJS?

I have three variables:

date = Tue Aug 02 2016 20:00:00 GMT-0400 (EDT);

startTime = Thu Jan 01 1970 09:00:00 GMT-0500 (EST)

endTime = Thu Jan 01 1970 10:00:00 GMT-0500 (EST)

I want to modify the startTime and endTime to keep their times, but use the date part from date. How can I accomplish this with momentjs?

like image 914
Shamoon Avatar asked Dec 02 '25 17:12

Shamoon


1 Answers

You can do this by using the get & set methods of moment:

var date = moment(new Date('Tue Aug 02 2016 20:00:00 GMT-0400 (EDT)'));
var startTime = moment(new Date('Thu Jan 01 1970 09:00:00 GMT-0500 (EST)'));
var endTime = moment(new Date('Thu Jan 01 1970 10:00:00 GMT-0500 (EST)'));

var year = date.get('year');
var month = date.get('month');
var day = date.get('day');

startTime.set({ year: year, month: month, day: day });
endTime.set({ year: year, month: month, day: day });

console.log(date.format(), startTime.format(), endTime.format());

Output (CST time zone):

2016-08-02T19:00:00-05:00 2016-08-02T08:00:00-05:00 2016-08-02T09:00:00-05:00
like image 85
JohnnyHK Avatar answered Dec 04 '25 07:12

JohnnyHK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!