Click here to Skip to main content
15,892,965 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Having problem in IF condition.

Please review my code

VB
 Dim dfrom As DateTime = Trim(dt.Rows(n - 1).Cells(2).Value) ' sample 07/08/2013
 Dim dto As DateTime = Trim(dt.Rows(n - 1).Cells(3).Value) 'sample 07/15/2013
Dim dnow As DateTime = Date.Now.ToString("MM/dd/yyyy")

If dnow >= dfrom AndAlso dnow <= dto Then
    MsgBox("Its working")
Else
    MsgBox(" Epic Fail!!! ")

End If


and i always get msgbox "Epic Fail". Lol
Posted

I suspect if the code you gave compiles without errors. Anyway, try using DateTime.Parse like following:

Dim dfrom As DateTime = DateTime.Parse(Trim(dt.Rows(n - 1).Cells(2).Value))


and dnow does not need to be converted to string - the comparison you can do in DateTime object itself. Should give correct result after that.
 
Share this answer
 
1. Casts cells from dt as DateTime datatype using CDATE()
2. Assumes that the two cells in dt only contain mm/dd/yyyy and do not contain any time data.
3. Saves only the date part of the current datetime in dnow variable using .Date property otherwise the compare for equal will fail.

VB
Dim dfrom As DateTime = CDATE(dt.Rows(n - 1).Cells(2).Value) ' sample 07/08/2013
Dim dto As DateTime = CDATE(dt.Rows(n - 1).Cells(3).Value) 'sample 07/15/2013
Dim dnow As DateTime = Date.Now.Date ' Use only Date part of current DateTime
If dnow >= dfrom AndAlso dnow <= dto Then
    MsgBox("Its working")
Else
    MsgBox(" Epic Fail!!! ")
End If
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900