How to Calculate the Date & Time Difference in Hours & Minutes in VBA

Written by ryan menezes
  • Share
  • Tweet
  • Share
  • Pin
  • Email
How to Calculate the Date & Time Difference in Hours & Minutes in VBA
Visual Basic calculates the time between appointments. (Jupiterimages/Photos.com/Getty Images)

Visual Basic computes dates using the DateTime structure. A DateTime variable stores a time in terms of its year, month and day, its hour, minute and second and even its milliseconds. A command that acts on DateTime variables, the DateDiff function, calculates the difference between the two times. It returns this difference in terms of whichever interval you specify, including days and years or hours and minutes.

Skill level:
Moderate

Other People Are Reading

Instructions

  1. 1

    Type the following line of code into your program:

    Dim firstDateTime As New System.DateTime(2012, 12, 21, 13, 04, 0, 00, cal)

  2. 2

    Replace "2012" in the line with the earlier time's year.

  3. 3

    Replace "12" with the number corresponding with the time's month, with "1" representing January, "2" representing February, and so on.

  4. 4

    Replace "21" with the day's date. "December 11th," for instance, would translate as "11."

  5. 5

    Replace "13" with the time's hour, using a 24-hour clock; "8:30 p.m.," for instance, translates as "20."

  6. 6

    Replace "05" with the time's minutes; "8:30 p.m.," for instance, translates as "30."

  7. 7

    Type, below the first line:

    Dim secondDateTime As New System.DateTime(2012, 12, 21, 13, 04, 0, 00, cal)

  8. 8

    Insert the later date and time into the line of code in the same fashion.

  9. 9

    Type the following code next:

    msg = "Difference between times: " & DateDiff(DateInterval.Hour, first Date, second Date) & "hours and" & (DateDiff(DateInterval.Minute, first Date, second Date) - DateDiff(DateInterval.Hour, first Date, second Date)) & "minutes"

    MsgBox(msg)

Don't Miss

Filter:
  • All types
  • Articles
  • Slideshows
  • Videos
Sort:
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the eHow.co.uk site, you consent to the use of cookies. For more information, please see our Cookie policy.