# Calculating time difference

Page 1 of 1

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

### #1 giant551

• New D.I.C Head

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: 3743
• Posts: 11,325
• 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

Was This Post Helpful? 0

### #3 andrewsw

• I'm not here to twist your niblets

Reputation: 4454
• Posts: 16,313
• 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
```

Was This Post Helpful? 0

Page 1 of 1

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }