none
Calculate difference between 2 dates in hours. RRS feed

  • Question

  • Hello, I'm trying to calculate the difference between 2 dates in hours as below

    Where the user will type the first date in in a textbox, select the time from a combobox, type the second date and select the second time from the second combobox.

    I want to have a third textbox that has the difference of the above values as number of hours, example 103, but I could not figure it out.

    Appreciate your help.

    Thanks

    Friday, December 16, 2016 4:39 PM

Answers

  • Sub Test()
      Dim T1, C1, T2, C2
      T1 = "10/10/2016"
      C1 = "0100 h"
      T2 = "15/10/2016"
      C2 = "0200 h"
      
      Dim A As Date, B As Date
      On Error GoTo Errorhandler
      A = CDate(T1) + Val(C1) / 2400
      B = CDate(T2) + Val(C2) / 2400
      
      Debug.Print Round(Abs(A - B) * 24, 1)
      Exit Sub
      
    Errorhandler:
      Debug.Print "Invalid dates"
    End Sub
    

    • Marked as answer by Ahmed Morsyy Friday, December 16, 2016 5:35 PM
    Friday, December 16, 2016 5:05 PM

All replies

  • Sub Test()
      Dim T1, C1, T2, C2
      T1 = "10/10/2016"
      C1 = "0100 h"
      T2 = "15/10/2016"
      C2 = "0200 h"
      
      Dim A As Date, B As Date
      On Error GoTo Errorhandler
      A = CDate(T1) + Val(C1) / 2400
      B = CDate(T2) + Val(C2) / 2400
      
      Debug.Print Round(Abs(A - B) * 24, 1)
      Exit Sub
      
    Errorhandler:
      Debug.Print "Invalid dates"
    End Sub
    

    • Marked as answer by Ahmed Morsyy Friday, December 16, 2016 5:35 PM
    Friday, December 16, 2016 5:05 PM
  • Thanks Andreas!
    Friday, December 16, 2016 5:36 PM