Date and Time problems

Raddy

Member
Joined
Nov 17, 2006
Messages
5
Programming Experience
1-3
I'm writing a program that I want calculate a date difference. The problem is that the end date (Now) is formatted the way I want with the date and the time, but the starting time is just the date. I want the calculation to befrom midnight on the specified date till Now. Here's the code:

VB.NET:
today = Now
        start = #1/4/2006#
        Format(today, "mm/dd/yyyy HH:mm:ss")
        Format(start, "mm/dd/yyyy HH:mm:ss")
        days = DateDiff(DateInterval.Day, start, today)
Any suggestions?
 
Firstly, please post in the most appropriate forum. This thread has been moved.

Secondly, those Format statements are doing absolutely nothing. Date objects have no format. They are just Date objects. Format is only an issue when converting to or from a string, which you do not need or want to do. Format will return the formatted string, which you are not assigning to a variable so you are immediately losing.

When you create a Date object it ALWAYS has a date and time portion. If you don't specify a time portion then it is implicitly midnight, i.e. 00:00:00. If you want to know the number of days from a particular date to today then you subtract that date from the current date to get a TimeSpan and then get the number of days from that:
VB.NET:
Dim days As Integer = Date.Today.Subtract(startDate).Days
Expanded that can look like this:
VB.NET:
Dim today As Date = Date.Today
Dim start As Date = #1/04/2006#
Dim time As TimeSpan = today.Subtract(start)
Dim days As Integer = time.Days
Note the non-use of any Runtime functions including Now, Format and DateDiff. Now and Format should never be used and Date.Now (current time) or Date.Today (current date) and String.Format used in there place. DateDiff can be useful for intervals greater than days but note that it is not completely accurate so it is preferable to create your own method using Date, TimeSpan and Calendar objects.
 
Back
Top