Skip to content
Advertisement

javascript add up date and time object in an array

so I have a list of array of time and date I want to join both appointmateDate and appointmentTime to iso format and get a new array of timeRange is that possible🙏🏻

const time = [
            {
                "appointmentDate": "2021-12-24T23:00:00.000Z",
                "appointmentTime": "17:51 am"
            },
            {
                "appointmentDate": "2021-12-24T23:00:00.000Z",
                "appointmentTime": "18:51 am"
            },
            {
                "appointmentDate": "2021-12-24T23:00:00.000Z",
                "appointmentTime": "19:51 am"
            },
            {
                "appointmentDate": "2021-12-24T23:00:00.000Z",
                "appointmentTime": "20:51 am"
            }
        ]

         console.log(time)

Advertisement

Answer

Using setHours.

Loop over the array using Array#map and create a new Date object using appointmentDate and then using setHours and appointmentTime set the time.

NOTE: 20:51 am is not a valid time, if it is in 24 hour format there’s no need for am, pm.

const 
  time = [{appointmentDate:"2021-12-24T23:00:00.000Z",appointmentTime:"17:51 am"},{appointmentDate:"2021-12-24T23:00:00.000Z",appointmentTime:"18:51 am"},{appointmentDate:"2021-12-24T23:00:00.000Z",appointmentTime:"19:51 am"},{appointmentDate:"2021-12-24T23:00:00.000Z",appointmentTime:"20:51 am"}],

  res = time.map(({ appointmentDate, appointmentTime }) => {
    const date = new Date(appointmentDate);
    const hour = appointmentTime.slice(0, 2);
    const min = appointmentTime.slice(3, 5);
    date.setHours(hour, min)
    return date.toISOString();
  });

console.log(res);

One Liner

Logic remains exactly the same, its just expressions instead of statements.

const 
  time = [{appointmentDate:"2021-12-24T23:00:00.000Z",appointmentTime:"17:51 am"},{appointmentDate:"2021-12-24T23:00:00.000Z",appointmentTime:"18:51 am"},{appointmentDate:"2021-12-24T23:00:00.000Z",appointmentTime:"19:51 am"},{appointmentDate:"2021-12-24T23:00:00.000Z",appointmentTime:"20:51 am"}],
  
  res = time.map(
    ({ appointmentDate, appointmentTime }, _i, _arr, d = new Date(appointmentDate)) => 
    (d.setHours(appointmentTime.slice(0, 2), appointmentTime.slice(3, 5)), d.toISOString())
  );

console.log(res);
Advertisement