我正在尝试使用 IF 语句比较 2 个日期,但似乎 Visual Basic 不会比较它们,因为我总是以 Else 上的 msgbox 结束,这是我的代码:
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:2021 年 6 月 21 日,15:22:35
CLParamDL:09/21/2017,17:02:00
我不知道为什么它不会进入 IF 语句。
答案 0 :(得分:3)
假设 SysDT 和 CLParamDL 都是 Date 类型,那么只需比较它们而不尝试将它们转换为字符串:
If theSysDT > CLParamDL Then
MsgBox ("theSysDt is greater than CLParamDL")
Else
MsgBox ("error error")
End If
答案 1 :(得分:-1)
尝试使用格式 yyyy/mm/dd
而不是 mm/dd/yyyy
以便日期字符串可以按字典顺序排序。
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
为什么这篇文章是正确答案?我们不应该直接比较两个日期吗?
虽然看起来最初的问题是问“如何比较两个日期”,但实际上并非如此。这是一个关于“如何以字符串格式规范化日期(以便可以使用普通字符串比较运算符将其与其他值进行比较)”的问题。因此,这篇文章可以是被接受的正确答案。在这种情况下,展示比较两个日期的直接方法毫无意义。
原代码解释:
一般来说,比较两个日期是通过直接比较两个日期来完成的,大家都知道(可能原发帖人也知道)。
If theSysDT > CLParamDL Then
MsgBox ("theSysDt is greater than CLParamDL")
Else
MsgBox ("error error")
End If
但是原来的代码不是这样写的,
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
因为它是一个 minimal test code
来澄清问题,“为什么日期-字符串不能按预期进行比较”。代码清楚地显示了 how date-strings are composed
和 how comparison is made
。由于所有元素都(太)紧凑地打包在单个 IF
子句中,因此尝试使用字符串比较来比较两个日期看起来像是一个笨拙的代码。但这是一个有目的地设计的正确代码。不带偏见地看原始问题,正确把握整个画面对我们来说很重要。