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
Calculating time difference
Page 1 of 12 Replies - 284 Views - Last Post: 26 January 2013 - 05:56 AM
Replies To: Calculating time difference
#2
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
from that you can calculate the difference in months/days/years/…
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
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
Page 1 of 1
|
|

New Topic/Question
Reply


MultiQuote



|