skip to Main Content

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?

2

Answers


  1. I don’t see a clear scenario of doing this. However, just simply pick the value directly from any defined Date value:

    const date1 = "2024-07-25T00:58:00.000Z";
    const date2 = "2024-07-30T13:35:00.000Z";
    
    const dt1 = new Date(date1);
    const dt2 = new Date(date2);
    
    // This should be combination value DateTime
    const combinedDate = new Date(
      Date.UTC(
        dt1.getUTCFullYear(),
        dt1.getUTCMonth(),
        dt1.getUTCDate(),
        dt2.getUTCHours(),
        dt2.getUTCMinutes(),
        dt2.getUTCSeconds(),
        dt2.getUTCMilliseconds()
      )
    );
    
    // Format the combined date back to ISO string
    const combinedIsoString = combinedDate.toISOString();
    
    console.log(combinedIsoString);
    
    Login or Signup to reply.
  2. 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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search