Javascript question | Sololearn: Learn to code for FREE!


Javascript question

I have a string of time inside a variable like string='03:47am-04:56am'. we need to find the difference between time in minutes. Can anyone help me how to solve this using javascript

9/21/2022 9:06:52 AM

krishna kishore

6 Answers

New Answer


const time= '03:47am-04:56am' const [firstTime,secondTime]=time.split("-") const [firstTimeHour,firstTimeMinute]=firstTime.split(':') const [secondTimeHour,secondTimeMinute]=secondTime.split(':') const result = (parseInt(secondTimeHour)*60+parseInt(secondTimeMinute))-(parseInt(firstTimeHour)*60+parseInt(firstTimeMinute)) console.log(`${result} minutes`)


What is your attempt, even if it's just pseudocode so you can be pointed in the right direction?


You need to convert data from string, if your string is always in same format you can separate tham by separator (-), you can use str.split("-") for this, but only if you will always have "-" in string, if not you should check is "-" in string before moving forward with code. More about split method: Now you will have array with 2 data let data = ["03:47am","04:56am"] You can now check is data am or pm, or convert to 24h format to calculate easier. For example if first data is pm, 03:00pm - 02:00am difference is not 1 hour it is 13h, thats why I will convert to 24h format. To separate hours and minutes you can also use str.split(":") but now separator is : Try to code it, if you have problem post your code attempt so we can help you.


✍️(◔◡◔) Hope this link helps you


krishna kishore if you are willing to learn and use cdn packages, Moment js is a convenient alternative Play around with the str variable in the javascript tab. Change the numbers, the am/pm ...


i gave 2 different time frames over there inside that string. I want to know the time difference between those 2-time frames in minutes. For example, if we take the above string the difference should be 69 minutes. like that I need it.