[RESOLVED] How many hours between two dates
Hi,
I have two dates that are stored as strings in the format 9/1/2011 5:00:00 PM.
I was hoping you could help me find an easy way to computer how many hours are between the two dates.
If date1 was 9/1/2011 5:00:00 PM
and date 2 was 9/2/2011 5:00:00 PM the answer would be 24
Thanks so much,
Re: How many hours between two dates
GB
Welcome to the Forums .. :wave:
Possibly something like this ..
Code:
hrs = DateDiff("h", date2, date1)
... where the "h" indicates the function returns "hours"
Spoo
Re: How many hours between two dates
Can I do that with strings? Or does date 2, and date 1 need to be Date?
Re: How many hours between two dates
Sure
Const date1 = "9/1/2011 5:00:00 PM"
Const date2 = "9/2/2011 5:00:00 PM"
MsgBox Abs(DateDiff("h", date2, date1))
Re: How many hours between two dates
If I read the date in from a textbox, can I just cast it do a date?
Re: How many hours between two dates
No need
MsgBox Abs(DateDiff("h", Text2.Text, Text1.Text))
Re: How many hours between two dates
O awesome. Thank you so much
Re: How many hours between two dates
Now that we've helped you, you can help us by marking the thread as resolved. If you have JavaScript enabled you can do that by selecting the Mark Thread Resolved item from the Thread Tools menu. Otherwise please insert "[Resolved]" at the start of the Subject and select the green checkmark from the Post Icons.
If someone has been particularly helpful you also have the ability to affect their forum 'reputation' by rating their post. Only those ratings that you give after you have 20 posts will actually count, but everyone you rate will know that you appreciate their help.
Re: [RESOLVED] How many hours between two dates
BTW I'd be remiss if I didn't mention how 'dangerous' it is to use textboxes that way. I don't know where the dates come from but when they are in a textbox the user can change them or just enter something that doesn't translate to a date so you should at least do something like this:
Code:
If Not IsDate(Text1.Text) Then
MsgBox "The text in Text1 is not a valid date"
Exit Sub
End If
If Not IsDate(Text2.Text) Then
MsgBox "The text in Text2 is not a valid date"
Exit Sub
End If
MsgBox Abs(DateDiff("h", Text2.Text, Text1.Text))
If the dates come from some source other than user input then you should probably use Labels instead of textboxes and in the formula use Label1.Caption instead of Text1.Text etc.