Search code examples
vb6

Visual Basic 6.0 IF statement won't go through, only keeps going to ELSE statement


I'm trying to compare 2 dates using IF statement but it seems that visual basic won't compare them since i always ended up with the msgbox that is on my Else, here is my code:

If Format(theSysDT, "mm/dd/yyyy HH:MM:SS") > Format(CLParamDL, "mm/dd/yyyy HH:MM:SS") Then
        MsgBox ("theSysDt is greater than CLParamDL")
Else
        MsgBox ("error error")
End If

theSysDT: 06/21/2021, 15:22:35

CLParamDL: 09/21/2017, 17:02:00

i don't know why it won't enter the IF statement.


Solution

  • Answer

    Try using format yyyy/mm/dd instead of mm/dd/yyyy so the date-strings can be sortable in dictionary order.

    theSysDT: 06/21/2021, 15:22:35 -> 2021/06/21 15:22:35

    CLParamDL: 09/21/2017, 17:02:00 -> 2017/09/21 17:02:00

    If Format(theSysDT, "yyyy/mm/dd HH:MM:SS") > Format(CLParamDL, "yyyy/mm/dd HH:MM:SS") Then
        MsgBox ("theSysDt is greater than CLParamDL")
    Else
        MsgBox ("error error")
    End If
    

    Appendix: Frequently Asked Question (about this Answer)

    How come this post is the right answer? Shouldn't we compare two Dates directly?

    Though it looks like the original question was launched to ask "how to compare two dates", but actually it's not so. It's a question regarding "how to canonicalize date in string format (so it can be compared with other values by using ordinary string comparison operators)". Therefore this post can be the correct answer to be accepted. Showing direct ways to compare two dates makes no sense in this case.

    Interpretation of the original code:

    In general, comparing two dates are to be done by direct comparison of two dates, as every one knows (probably the original poster also knows).

    If theSysDT > CLParamDL Then
        MsgBox ("theSysDt is greater than CLParamDL")
    Else
        MsgBox ("error error")
    End If
    

    But the original code was not written as such,

    If Format(theSysDT, "mm/dd/yyyy HH:MM:SS") > Format(CLParamDL, "mm/dd/yyyy HH:MM:SS") Then
        MsgBox ("theSysDt is greater than CLParamDL")
    Else
        MsgBox ("error error")
    End If
    

    Because it is a minimal test code to clarify the problem, "why date-strings cannot be compared as expected". The code is clearly showing both how date-strings are composed and how comparison is made. Since all the elements were packed (too) compactly in a single IF clause, it looks like an awkward code for attempting to use string comparison to compare two dates. But it's a right code which was purposefully designed as such. It's important for us to grasp the entire picture correctly by seeing the original question without prejudice.