I have a output resulting from a timepicker giving 12 hour format of time.
Eg : \"1:45 AM (or) \"12:15 PM\" as **string**
Is there a way to par
Here's how you can set the time of a Date
object using a time String
.
const date = new Date('1/1/21');
const pm = '2:30 PM';
const am = '11:00 AM';
const noon = '12:00 PM';
const midnight = '12:00 AM';
const mergeDateTime = (date, time) => {
const parsedTime = moment(time, ['h:mm A']);
const merged = moment(date).set({
hours: parsedTime.get('hours'),
minutes: parsedTime.get('minutes')
});
return merged.toDate();
};
const resultsList = document.querySelector('#results');
const inputs = [pm, am, noon, midnight];
inputs.forEach((input) => {
const li = document.createElement('li');
li.innerText = `${input} ➡ ${mergeDateTime(date, input)}`;
resultsList.appendChild(li);
});
Results