Easily manipulate time using javascript

December 9th, 2016 Javascript 413 views

Calculating time has been a headache for developers from long time. Specially when you have to do it using javascript, it’s definitely a nightmare. But moment.js has made it very easy now. Moment.js is used to parse, validate, manipulate, and display dates in JavaScript. You can download it from here http://momentjs.com/

Recently I got a job to calculate time from a timesheet. In which people fill in Start Time, Break Time, Finish Time & Overtime. And I had to calculate total working time. So the formula goes something like this.

Start Time + Finish Time + Overtime – Luch Break = Total Working Hours

So first we have the values like this.

Next, we have to split out all time into hours and minutes. So it will be done like this.

Now what we need is the time difference between Start Time & End Time.
We can get the difference like this using moment.js

Here you can see moment.js provides a very simple .diff() method. Which will give you difference between 2 time. And in the end I have formatted it into Hours. The reason to pass these values into moment() method is because they are string and then need to be converted into ‘moment’ object to take full advantage of it’s methods.

Now next we have to add overtime to this difference. But for that we have to convert this difference into ‘duration’ object.

And using duration object, we can easily add our ovetime to the time difference we got.

The reason why I had to use 2 separate lined for hours and minutes is because the add() method supports only one unit at a time. Now same way, we will subtract break time.

And finally format the end result which is total working hours.

And That’s it. That was pretty quick to do. The final script will look like this.

 

Leave your comments: