Categories
JavaScript Answers

How to merge two dates in JavaScript?

Spread the love

Sometimes, we want to merge two dates in JavaScript.

In this article, we’ll look at how to merge two dates in JavaScript.

How to merge two dates in JavaScript?

To merge two dates in JavaScript, we can get the parts from each date and put it in a new date.

For instance, we write:

const date = new Date('Wed Dec 21 2022 00:00:00 GMT+0000 (GMT)')
const time = new Date('Sun Dec 31 2000 03:00:00 GMT+0000 (GMT)')
const datetime = new Date(date.getFullYear(), date.getMonth(), date.getDate(),
  time.getHours(), time.getMinutes(), time.getSeconds());
console.log(datetime)

to combine the date and time into datetime.

We get the year, month, and day from date with getFullYear, getMonth, and getHours.

And then we get the hours, minutes, and seconds with getHours, getMinuts, and getSeconds.

As a result, we get that datetime is 'Tue Dec 20 2022 19:00:00 GMT-0800 (Pacific Standard Time) '.

Conclusion

To merge two dates in JavaScript, we can get the parts from each date and put it in a new date.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *