4

The DateDiff function reports Day Intervals on a 24 hour basis, which provides an odd result when asking how many days ago something happened when the time of day changes.

For example, if I want to get the number of days since yesterday afternoon, if it hasn't been a full 24 hours, DateDiff will return 0, whereas most of the time I ask that question, I'm expecting yesterday to be treated as 1 day ago, regardless of timestamp.

Is there a way to get DateDiff to return the number of calendar days?

Demo in .NET Fiddle

Dim date1 As DateTime = #3/1/2017 5:00 PM#
Dim date2 As DateTime = #3/2/2017 10:00 AM#

Dim daysAgo = DateDiff(DateInterval.Day, date1, date2)
Dim msg = String.Format("Last date was {0} day(s) ago on {1}. ", daysAgo, date1.ToShortDateString())
Console.WriteLine(msg) ' Last date was 0 day(s) ago on 3/1/2017. 

The following questions on StackOverflow do not address this nuance:

Community
  • 1
  • 1
KyleMit
  • 30,350
  • 66
  • 462
  • 664

2 Answers2

10

You don't need string manipulation to get a DateTime without the time part, just use DateTime.Date.

To get the time span between two dates, just subtract one from the other. Subtracting one date from another returns a TimeSpan object whose Days property is the difference in full dates.

All you need to do is :

Dim days As Integer =(date2.Date-date1.Date).Days 

This way you avoid generating and parsing temporary strings.

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
0

You can use DateTime.Date to remove the time component and compare the whole number dates like this:

Demo in .NET Fiddle

Dim date1 As DateTime = #3/1/2017 5:00 PM#
Dim date2 As DateTime = #3/2/2017 10:00 AM#

Dim daysAgo = DateDiff(DateInterval.Day, date1.Date, date2.Date)
Dim msg = String.Format("Last date was {0} day(s) ago on {1}. ", daysAgo, date1.ToShortDateString())
Console.WriteLine(msg) ' Last date was 1 day(s) ago on 3/1/2017. 
KyleMit
  • 30,350
  • 66
  • 462
  • 664