0

I need a function to get hours from two variable (date+time)

var a date +time

var b date +time

result = a-b in hours
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Dev
  • 51
  • 1
  • 8
  • What type of data do the two variables hold - are they date objects, strings, or something else? – Anthony Grist Mar 08 '11 at 13:01
  • http://stackoverflow.com/questions/327429/whats-the-best-way-to-calculate-date-difference-in-javascript –  Mar 08 '11 at 13:08

3 Answers3

1

in ASP VBScript, the DateDiff function will do business

result = DateDiff('h', a, b)

  • This is fine , but how can I call it on client side ? eg. – Dev Mar 09 '11 at 07:54
  • you can't - ASP is server-side. All you can do is output the result directly, eg `">` or as the return value from an AJAX call. If you want 100% client-side you'd use the javascript method –  Mar 09 '11 at 08:49
  • Hi, I have working on this code "dim m1 , m2 , m3 m1 = request.Form("outdate")&" "& request.Form("outtime") m2 = request.Form("indate") &" " & request.Form("intime") m3 = DateDiff("h",m1,m2) but this gives errors datatype mismatch – Dev Mar 14 '11 at 06:16
  • @Dev without knowing what's really in the `Form` collection, I can't tell you but you could try explicitly converting `m1` and `m2` to dates before the `DateDiff` with `CDate()` –  Mar 14 '11 at 08:29
0

In javascript, use the UTC() function. It will return the milliseconds since 1/1/1970. Get the difference between the to values and convert to hours.

CheeZe5
  • 975
  • 1
  • 8
  • 24
0

The javascript Date object internally stores dates as integers, counting the number of milliseconds since 0:00 on January 1st, 1970.

Thus, adding/subtracting two JS dates from each others will result in the difference between the two, in millisconds. Converting those to hours is easy when you know there’s 60 * 60 * 1000 = 3 600 000 ms in one hour:

var a = new Date(old),
    b = new Date(newer),
    hoursBetween = (b - a) / 3600000;
Martijn
  • 13,225
  • 3
  • 48
  • 58
  • function dif() { var fromDate = document.form1.outdate.value + document.form1.outtime.value ; var toDate = document.form1.indate.value + document.form1.intime.value ; var a = new Date(fromDate), b = new Date(toDate), hoursBetween = (a - b) / 3600000; alert(hoursBetween); – Dev Mar 09 '11 at 08:01