0

Possible Duplicate:
Difference between dates in JavaScript

I've found myself at a javascript brick wall.

I would like to find the difference (in hours and minutes) between two times on two different days.

I can produce the hours, minutes and day of the week for each but cannot work out how to implement a function that will check how long there is until the next time.

Example:

If it's 16:00 on Friday and the next time is Monday at 13:00 the output would be 69 hours and 0 minutes.

Anyone got any ideas on how best to implement this?

N.B. I'm heavily using Google Closure.

Community
  • 1
  • 1
A_Porcupine
  • 1,008
  • 2
  • 13
  • 23
  • 1
    Please share some code to start with – wakooka Dec 27 '12 at 11:37
  • If you don't mind using additional libraries, Moment.js has great functionality for doing the kinda problems you stated. – Simon Dec 27 '12 at 11:41
  • Regarding the Google Closure Library, have a look at the API reference: http://closure-library.googlecode.com/svn/docs/closure_goog_date_date.js.html (but after a quick glance, I did not find any method to compute differences). – Felix Kling Dec 27 '12 at 11:42
  • Are the input values *datetimes* or *patterns*? I.e. does "16:00 on Friday" mean "16:00 on any friday" (pattern) or "2012-12-28 16:00:00 CEST" (datetime)? – Deestan Dec 27 '12 at 12:30

2 Answers2

1
var yourTimeStart = 'Friday 16:00'; //Your input
var yourTimeStop = 'Monday 13:00'; //Your input


var days = Array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");

var differenceDays = days.indexOf(yourTimeStop.split(" ")[0]) - days.indexOf(yourTimeStart.split(" ")[0]);
if (days.indexOf(yourTimeStart.split(" ")[0]) > days.indexOf(yourTimeStop.split(" ")[0])) differenceDays = differenceDays + 7;

var timeStart = yourTimeStart.split(" ")[1];
var timeStop = yourTimeStop.split(" ")[1];

var differenceHours = timeStop.split(":")[0] - timeStart.split(":")[0];
var differenceMins = timeStop.split(":")[1] - timeStart.split(":")[1]

var resultHours = differenceDays*24 + differenceHours;;


if (differenceMins < 0) {
    resultHours--;
    differenceMins = 60 + differenceMins; // differenceMins is negative
}

if (resultHours < 0) resultHours = resultHours + 7*24; //(this is if a you calculate the time between for example Monday 16:00 and Monday 12:00)

document.write(resultHours + " hour(s) and " + differenceMins + " minutes."); //output
JohannesB
  • 1,995
  • 21
  • 35
0

For Example :

var dte = new DateTime(2012, 12, 26,1,0,0);
var dte2 = new DateTime(2012, 12, 27, 18, 5, 0);

var totalHours = (int) dte2.Subtract(dte).TotalHours;
var totalMin = dte2.AddHours(-totalHours).Subtract(dte).TotalMinutes;


Console.WriteLine(totalHours.ToString());
Console.WriteLine(totalMin.ToString());