How to subtract hour from DateTime in VB

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Brian Connelly
    New Member
    • Jan 2011
    • 103

    How to subtract hour from DateTime in VB

    I have a line of code which consists of two variables. One is a string called "endTime" that is formated like 05:00 PM the other is a string called "overTime" that is formated like "1". What I am trying to do is subtract the overTime from the endTime. I have the following line that converts the strings to Dates, however the subtraction returns 12:00 AM, but I am expecting 04:00 PM. Here is the code line:
    Code:
    timeDiff = CDate(endTime) - Hour(CDate(overTime))
    Can anyone tell me what I am doing wrong and how I should go about it?
  • zmbd
    Recognized Expert Moderator Expert
    • Mar 2012
    • 5501

    #2
    Why not use the datediff() function?

    Comment

    • Brian Connelly
      New Member
      • Jan 2011
      • 103

      #3
      Originally posted by zmbd
      Why not use the datediff() function?
      http://msdn.microsoft.com/en-us/libr...(v=vs.80).aspx
      DateDiff would return the diff. in time between and one is a date the other was not. The actual solution to what I was tring to do used dateAdd(). The code is this:
      Code:
      timeDiff = DateAdd("h", overTime * -1, endTime)
      The "h" is the metric of an hour, the overTime * -1 makes the value a negative (so Im adding a negative number to the time, and the endTime is the Time variable that I am changing.

      I do appreciate your response and help.

      Comment

      • zmbd
        Recognized Expert Moderator Expert
        • Mar 2012
        • 5501

        #4
        ... and yet your op and the code you posted were for date data types.

        So... you are after what exactly? Something along the lines of if Sam worked three hours of overtime and Sam punched off the clock at 17h00 at what time did Sam's regular time end? (answer is 14h00) If that was what you were after, and had worded your question along that lines, then my answer would have been to use the dateadd() as you have done.

        Comment

        • Killer42
          Recognized Expert Expert
          • Oct 2006
          • 8429

          #5
          Probably the DateAdd function would be more appropriate.

          The way it's used may vary depending on your version of VB. I've linked to the doco for VB6.

          Comment

          Working...