15,938,122 members
1.00/5 (1 vote)
See more:
Hi

Using javascript I want to calculate hours between 2 times along with lunch break.

EG:
Start Time - 9:00 AM
End Time - 5:00 PM
Lunch Time - 0.30(i.e 30 minutes)

Output should Be: 7.30 hours.

Thanks,
Meenakshi
Posted
Mohibur Rashid 30-Oct-15 4:06am
have tried searching online?

## Solution 1

• Parse the strings to obtain a common unit (e.g. minutes)

```9:00 AM ->  9*60 ->  540
5:00 PM -> 17*60 -> 1020
0.30 -> 30```

• Subtract both Start Time end Lunch Time from End Time

`1020 - 540 - 30 -> 450`

• Convert the result from total minutes to hours and minutes

`450 -> 7*60 + 30 -> 7.30`

Krunal Rohit 30-Oct-15 4:51am
Looks good to me. :-)

-KR
CPallini 30-Oct-15 6:57am
Thank you.
Meenakshi_V 30-Oct-15 7:19am
Yeah this looks good.
What to do in case of below condition?

Start Time - 9:30 AM
End Time - 5:30 PM
Lunch Time - 0.30(i.e 30 minutes)

Output should Be: 7.30 hours.

Thanks,
Meenakshi
Meenakshi_V 30-Oct-15 7:39am
Got Them..I should be
9:30 AM -> 9*60+30-> 570
5:30 PM -> 17*60+30 -> 1050
0.30 -> 30

## Solution 2

You can make use of http://momentjs.com/[^]

Sample code
C#
```var StartTime = moment("9:00 am", "hh:mm a");
var EndTime = moment("5:00 pm", "hh:mm a");
var Lunch = moment("0.30", "hh.mm");
var TotalTime = ((EndTime.subtract(StartTime)).subtract(Lunch)).format("hh.mm");```

Regards..