I am setting the base time below
const baseTime = "9:00:00 AM"
const convertedTime = new Date();
const hour = baseTime.substring(0, baseTime.indexOf(':'));
const minuite = baseTime.split(':')[1];
convertedTime.setHours(parseInt(hour))
convertedTime.setMinutes(parseInt(minuite))
How can I also set either the AM or PM value, because it always display PM even when the baseTime is AM
CodePudding user response:
To set the AM or PM value of a Date object in JavaScript, you can use the setUTCHours method and pass in the desired hour, minute, and second values, as well as a value of 0 or 12 to indicate AM or PM.
If you want to set it to 9 PM, you can try out the following:
const baseTime = "9:00:00 PM";
const convertedTime = new Date();
const hour = baseTime.substring(0, baseTime.indexOf(':'));
const minute = baseTime.split(':')[1];
convertedTime.setUTCHours(parseInt(hour) 12, parseInt(minute), 0, 0);
Do upvote if you find this answer useful :)