Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert time string ("hours:minute") to date object

Here is time string with hours and minutes (e.g. "03:37"). I want to update date object that time and create date object in ember JS. Help me with this. The time goes by 24 hours.

like image 239
see Avatar asked Mar 05 '26 15:03

see


2 Answers

You could simply do the following:

const time = "03:37";
const [ h, m ] = time.split(":");
const ms = new Date().setHours(h,m);
const date = new Date(ms)
like image 71
Victor Karangwa Avatar answered Mar 07 '26 04:03

Victor Karangwa


Use the substring() function to extract the hours and minutes. Then use the setHours() function to assign them to any date object.

const today = new Date();

const timeString = "03:37";

// Use the substring() function to extract hours and minutes
const hours = timeString.substring(0,2);
const minutes = timeString.substring(3,5);

// Use the setHours() function to assign hours and minutes
// to the "today" date object
const modifiedDate = new Date(today.setHours(hours, minutes));

console.log(modifiedDate);
like image 43
Lahiru Tennakoon Avatar answered Mar 07 '26 04:03

Lahiru Tennakoon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!