Divide the given string input into hours and minutes. Proceed by instantiating a Date
object and adjusting the hours and minutes using the available Date.prototype.setHours()
and Date.prototype.setMinutes()
methods within the Date
class.
const input = '13:45';
const [hour, minutes] = input.split(':');
const today = new Date();
today.setHours(hour);
today.setMinutes(minutes);
console.log(today);
Date.prototype.setHours()
method also supports optional minutes, seconds, and milliseconds as arguments, making it convenient to modify time values with just the setHours()
method.
const input = '13:45';
const today = new Date();
today.setHours(...input.split(':'));
console.log(today);
Edit:
If you are utilizing Typescript and encounter errors when using spread syntax in the second code snippet above, consider updating your code to the following format:
const input = '13:45';
const today = new Date();
today.setHours(...input.split(':').map(Number) as [number, number]);
console.log(today);