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🙏🏻
JavaScript
x
20
20
1
const time = [
2
{
3
"appointmentDate": "2021-12-24T23:00:00.000Z",
4
"appointmentTime": "17:51 am"
5
},
6
{
7
"appointmentDate": "2021-12-24T23:00:00.000Z",
8
"appointmentTime": "18:51 am"
9
},
10
{
11
"appointmentDate": "2021-12-24T23:00:00.000Z",
12
"appointmentTime": "19:51 am"
13
},
14
{
15
"appointmentDate": "2021-12-24T23:00:00.000Z",
16
"appointmentTime": "20:51 am"
17
}
18
]
19
20
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
.
JavaScript
1
12
12
1
const
2
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"}],
3
4
res = time.map(({ appointmentDate, appointmentTime }) => {
5
const date = new Date(appointmentDate);
6
const hour = appointmentTime.slice(0, 2);
7
const min = appointmentTime.slice(3, 5);
8
date.setHours(hour, min)
9
return date.toISOString();
10
});
11
12
console.log(res);
One Liner
Logic remains exactly the same, its just expressions instead of statements.
JavaScript
1
9
1
const
2
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"}],
3
4
res = time.map(
5
({ appointmentDate, appointmentTime }, _i, _arr, d = new Date(appointmentDate)) =>
6
(d.setHours(appointmentTime.slice(0, 2), appointmentTime.slice(3, 5)), d.toISOString())
7
);
8
9
console.log(res);