开发者

Confusion when comparing StartDate and EndDate in asp.net

I am a bit confused when comparing StartDate and EndDate in my asp.net app.

EndDate:    10/1/2011
StartDate:  9/30/2011

The if statement below returns true, based on t开发者_如何学JAVAhe date values above.

If strEndDate < strStartDate Then

I would think the If statement shoudl return false. The concept is supposed to be that if EndDate is earlier than StartDate, display an error message.


I'm assuming that since your variables are called strEndDate and strStartDate that they're strings, not DateTimes. Since they're strings, and since '1' < '9' (the first characters in the strings), strEndDate is indeed "less than" strStartDate.

Convert the values to DateTime before comparing:

If DateTime.Parse(strEndDate) < DateTime.Parse(strStartDate) Then
    '...
End If


If those are DateTime variables, that code should evaluate to true. If not, you should convert them to DateTime.

DateTime start = DateTime.Parse(strStartDate);
DateTime close = DateTime.Parse(strEndDate);

if (close > start)
    //do something

You can also compare them like this:

if ((close - start).TotalDays > 0)
    //do something

As Rick Schott pointed out, you can also use DateTime.Compare


You should be using DateTime.Compare.

Dim date1 As Date = DateTime.Parse(strStartDate)
Dim date2 As Date = DateTime.Parse(strEndDate)
Dim result As Integer = DateTime.Compare(date1, date2)
Dim relationship As String

If result < 0 Then
   relationship = "is earlier than"
ElseIf result = 0 Then
   relationship = "is the same time as"         
Else
   relationship = "is later than"
End If

Console.WriteLine("{0} {1} {2}", date1, relationship, date2)
' The example displays the following output:
'    8/1/2009 12:00:00 AM is earlier than 8/1/2009 12:00:00 PM


Don't compare them as strings, compare them as dates.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜