KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: A generic method to calculate time difference
PRODUCT: 4D | VERSION: 15.x | PLATFORM: Mac & Win
Published On: November 8, 2016

The following is a generic method that will calculate time difference from Date-Time A to Date-Time B.


  // ----------------------------------------------------
  // Method: calculateElapsedTime
  // Description
  //    Returns the time difference between the given date and time range.
  //
  // Parameters
  //   $1   -   Start date
  //   $2   -   Start time
  //   $3   -   End date
  //   $4   -   End time
  //
  // Returns
  //  $0   -   Time difference
  // ----------------------------------------------------

C_TIME($0)
C_DATE($1;$startDate_d)
C_TIME($2;$startTime_h)
C_DATE($3;$endDate_d)
C_TIME($4;$endTime_h)

If (Count parameters>=4)

  $startDate_d:=$1
  $startTime_h:=$2
  $endDate_d:=$3
  $endTime_h:=$4

  C_TIME($timeElapsed_h)
  C_LONGINT($oneDay_l;$start_l;$end_l;$diff_l;$dayElapsed_l;$hourElapsed_l)

  $oneDay_l:=24*60*60  // in seconds

    // Get the total elapsed time in seconds
  $start_l:=(($startDate_d-!2001-01-01!)*$oneDay_l)+$startTime_h
  $end_l:=(($endDate_d-!2001-01-01!)*$oneDay_l)+$endTime_h
  $diff_l:=$end_l-$start_l

    // If the total elapsed time is more than one day, calculate
    // the total number of time (24hr x Number of days)
  $dayElapsed_l:=($diff_l\$oneDay_l)*$oneDay_l
  If ($dayElapsed_l>0)
    $timeElapsed_h:=?24:00:00?+$dayElapsed_l
  End if 

    // Calculate the remainder of time and add it
    // to the total time from the top
  $hourElapsed_l:=Abs($dayElapsed_l-$diff_l)
  $0:=$timeElapsed_h+(?00:00:00?+$hourElapsed_l)

End if 


Example:

$TotalTime_h:=calculateElapsedTime($startDate_d;$startTime_h;$endDate_h;$endTime_h)