29

I want to compare just the date part (and Not the time) of two VB.NET Date objects. Is there a way to do that?

Alex Angas
  • 59,219
  • 41
  • 137
  • 210
Ylva D
  • 355
  • 1
  • 4
  • 10

6 Answers6

65

Just take the date part of each via the Date property and compare the two:

date1.Date.CompareTo(date2.Date)

Or:

If date1.Date < date2.Date Then
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I'll remove the text about it then. Just for anyone following along, Konrad's comment made sense at the time :) – Jon Skeet Mar 06 '09 at 13:44
  • Thanks Jared. When I answer VB questions there's almost always a bit of syntactic guesswork involved :) – Jon Skeet Mar 06 '09 at 14:14
8

You could also use TimeSpan

Dim ts As TimeSpan
ts = dt1 - dt2

ts.Days will now have the difference of the two dates as whole days.

7

Compare the DateTime.Date properties.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
6

Change the txt1 date to format dd/mm/yyyy using myDateTime.ToShortDateString() so that both the dates will be in same format. then :

if (DateTime.Compare(date1, date2) > 0) 
// which means ("date1 > date2")
if (DateTime.Compare(date1, date2) == 0) 
//which means ("date1 == date2");
if (DateTime.Compare(date1, date2) < 0) 
//which means ("date1 < date2");
Brian Webster
  • 30,033
  • 48
  • 152
  • 225
0
Dim backDateCount As Integer = DateDiff(DateInterval.Day, CDate(dtpCheckIn.SelectedDate.Value).Date, Date.Now.Date)

Date.Now.Date: #12/4/2018 12:00:00 AM#

Date.Now: #12/4/2018 03:23:34 PM#

sun sreng
  • 587
  • 6
  • 7
-2
Dim date1, date2 As Date
date1 = Date.Parse(dtpStart.Text)
date2 = Date.Parse(dtpEnd.Text)
If (DateTime.Compare(date1, date2) > 0) Then ' which means ("date1 > date2") 
    MessageBox.Show("يجب تحديد  الفترة للتاريخ بشكل صحيح  ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RtlReading)
    Exit Sub
End If
Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121