Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get calendar days between two dates

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:

  • Get date difference in VB.NET
  • Calculating Number of Months between 2 dates
  • How to find the number of days between two dates / DateTimePickers
like image 669
KyleMit Avatar asked Feb 04 '23 23:02

KyleMit


1 Answers

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.

like image 200
Panagiotis Kanavos Avatar answered Feb 08 '23 17:02

Panagiotis Kanavos