Comparing Dates?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

How can compare two dates in terms of months. i.e.

01/08/2004 = 10/08/2004

05/08/2004 < 01/08/2005

thanx
 
Hi Job,

You can create 2 datetime objects and compare the months of the individual
objects.

DateTime dt1=new DateTime(2004,7,10);
DateTime dt2=new DateTime(2004,8,1);
if(dt1.Month < dt2.Month)
{
MessageBox.Show("dt1 < dt2");
}
 
One option is to compare the month and year parts of the dates separately.

How can compare two dates in terms of months. i.e.

01/08/2004 = 10/08/2004

05/08/2004 < 01/08/2005

thanx
 
The approaches that have been offered work if you don't want to take the year
into account as well. In other words, if you want August 9, 2004 to equal
August 9, 2005, you can simply compare the .Month property of the DateTime
objects.

However, the following example accounts for months AND years. It is a
little bit longer, but very straightforward.

'Start with your original DateTime values
Dim date1 As DateTime = DateTime.Parse("August 5, 2004")
Dim date2 As DateTime = DateTime.Parse("February 1, 2005")

'Create "Month-Only' versions of those values
Dim month1 As New DateTime(date1.Year, date1.Month, 1)
Dim month2 As New DateTime(date2.Year, date2.Month, 1)

'Now compare
If month1 < month2 Then
MsgBox("less")
ElseIf month1 > month2 Then
MsgBox("more")
Else
MsgBox("equal")
End If
 
Back
Top