Calculating time difference

Page 1 of 1

2 Replies - 1532 Views - Last Post: 26 January 2013 - 05:56 AM

#1 giant551

Reputation: 0
• Posts: 1
• Joined: 26-January 13

Calculating time difference

Posted 26 January 2013 - 01:33 AM

Hi everyone

I am just starting my long journey into learning javascript! I'm not a natural programmer so everything feels like i am being constantly slapped around the face with a wet fish. Anyway i was just wondering if anyone could point me i the right direction with a current project.

I would like to be able to calculate the difference between 2 times and not sure how to implement it. I'm not sure if its best to use a time picker plug in or use moment.js? i've found quite a bit of examples of date manipulation but not hours and minutes.

the best solution would be the user just types in 2 times and hits a calculate button. i can do this with normal numbers but time i am a little lost where to start?

Thanks for any help

Paul

Is This A Good Question/Topic? 0

Replies To: Calculating time difference

#2 Dormilich

• 痛覚残留

Reputation: 4184
• Posts: 13,226
• Joined: 08-June 10

Re: Calculating time difference

Posted 26 January 2013 - 01:41 AM

the question rather is, what type of result do you expect? the most simple way is using the difference in milliseconds
```var date1 = new Date(2012, 5, 6), // June 6, 2012
date2 = new Date(2012, 3, 13); // April 13, 2012

console.log(date1 - date2); // 4665600000
```

from that you can calculate the difference in months/days/years/…

This post has been edited by Dormilich: 26 January 2013 - 01:42 AM

#3 andrewsw

• blow up my boots

Reputation: 6541
• Posts: 26,471
• Joined: 12-December 12

Re: Calculating time difference

Posted 26 January 2013 - 05:56 AM

If I assume that the user enters two times in the format "08:00", "14:20:25", and we save these as variables timeStart, timeEnd - and that you are only interested in the time difference within the same 24 hour period, then one approach is:

```var timeStart = "08:00";
var timeEnd = "14:20:15";
var dtStart = new Date("2013/1/1 " + timeStart);
var dtEnd = new Date("2013/1/1 " + timeEnd);
var dtDiff = (dtEnd - dtStart)/(1000 * 60); // number of minutes (plus fraction)
var dtMins = parseInt(dtDiff);
console.log(dtDiff);    // 380.25
console.log(dtMins);    // 380
```