I had something that I thought was a simple task and got the solution for it, but when I researched it, I didn’t see a whole lot of other people talking about it. Actually, in my brief searches, I didn’t see anyone talking about it. So here goes.
What do you do if you want to add a time to a date? Most people would say, “Duh. A date is a time. That’s why they call it DateTime.” But say for the sake of argument, you have two variables, one holds a date and one holds a time. The time portion is irrelevant in your date variable because you always use .ToShortDateString and likewise with the time variable always using .ToShortTimeString. Now you want them together.
Take the following block of code:
Dim baseDate As DateTime
Dim newDate As DateTime
baseDate = DateTime.Now
newDate = New Date(2012, 12, 20)
' Insert here
MsgBox(baseDate.ToString & " = " & newDate.ToString)
Which statement placed in “Insert here” will be the most efficient, judging by IL code generated?
' Version 1
newDate = newDate.AddHours(baseDate.Hour) _
.AddMinutes(baseDate.Minute) _
.AddSeconds(baseDate.Second) _
.AddMilliseconds(baseDate.Millisecond)
' Version 2
newDate = Date.Parse(newDate.ToShortDateString _
& " " & baseDate.ToLongTimeString)
' Version 3
newDate = newDate.Date.Add(baseDate.Subtract(baseDate.Date))
You might be surprised like I was, but #2 is the best, unless you need millisecond precision, then #2 is disqualified, making #3 the best. Probably no surprise, #1 is the worst because every .Add[interval] call creates a new temporary value in IL.
You might be looking at #1 thinking “Who would do something like that?” When I first had the need to add a date and a time, I considered that route for about a second and thought there has to be a better way. I settled on using #3, figuring if I added a time with zero days on it (by subtracting out the date portion) it would give me the TimeSpan structure I needed to add to the date portion of my original date.
TimeSpan is a really nice structure that probably doesn’t get as much exposure as some other .NET elements like StringBuilder.