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

#1 giant551  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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  Icon User is online

  • 痛覚残留
  • member icon

Reputation: 3402
  • View blog
  • Posts: 9,619
  • 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  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 2890
  • View blog
  • Posts: 9,597
  • 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