javascriptdate

How to create a new date by using one's date part and other's time part?


I have 2 dates in ISO string format. I mean 2024-07-25T00:58:00.000Z and 2024-07-30T13:35:00.000Z. I am trying to make them combine as 2024-07-25T13:35:00.000Z. Is there a way to do this with a simple solution?


Solution

  • You can split date and time with .split('T') and you can concatenate strings with +.

    const date1 = '2024-07-25T00:58:00.000Z';
    const date2 = '2024-07-30T13:35:00.000Z';
    
    function combineDates(date1, date2) {
      return date1.split('T')[0] + 'T' + date2.split('T')[1];
    }
    
    console.log(combineDates(date1, date2));
    
    const expectedDate = '2024-07-25T13:35:00.000Z';
    console.log(combineDates(date1, date2) === expectedDate);