【问题标题】:Find if date is more than another date查找日期是否大于另一个日期
【发布时间】:2013-03-04 05:24:42
【问题描述】:

我不知道为什么这个 VB.net 代码不起作用..

我要做的是if value1 > value2 然后显示一个消息框说已过期,否则显示一个消息框说未过期。

If "4-3-13 10:54:22" > "15-3-13 12:23:30" Then
    MsgBox("Expired")
Else
    MsgBox("Not Expired")
End If

每次都说过期,即使知道它不应该。

当我将其从 15-3-13 12:23:30 更改为 1-3-13 12:23:30 时,它仍然显示已过期。

如果我将代码更改为:

If "4-3-13 10:54:22" < "15-3-13 12:23:30" Then
    MsgBox("Not Expired")
Else
    MsgBox("Expired")
End If

它仍然返回错误。

如何做到这一点:

DATE1 = 4-3-13 10:54:22

DATE2 = 15-3-13 12:23:30


IF DATE1 > DATE2 THEN
   Expired
else
   Not Expired

应该返回“未过期”

任何人都可以帮助..我不能工作吗?

【问题讨论】:

    标签: vb.net date datediff


    【解决方案1】:
    "4-3-13 10:54:22" > "15-3-13 12:23:30" 
    'This condition states that you are comaparring strings not date
    

    为了得到你期望的结果,这样做,

    cdate("4-3-13 10:54:22") > cdate("15-3-13 12:23:30")
    'Convert the strings into date and then compare it.
    

    CDATE

    【讨论】:

    • 除非您明确设置了文化,否则不要在文字字符串上使用 cdate。否则,对于计算机日期格式不同的不同国家/地区的人们,它会抛出异常或给出错误的结果。
    【解决方案2】:

    这些date constants 也将按照您的预期进行,并且在程序运行时不受语言环境的影响:

    #3/4/2013 10:54:22# > #3/15/2013 12:23:30#
    

    请记住,您需要对常量使用美国日期格式。

    【讨论】:

      【解决方案3】:

      试试这个:

      dim date1 as DateTime = DateTime.ParseExact("4-3-13 10:54:22", "MM-dd-yy HH:mm:ss")
      
      dim date2 as DateTime = DateTime.ParseExact("15-3-13 12:23:30", "MM-dd-yy HH:mm:ss")
      
      if date1 > date2 then
      MsgBox("Expired")
      else
      MsgBox("Not Expired")
      end if
      

      【讨论】:

        【解决方案4】:

        代码如下:

        If Today.Year - dExpiryDate.Value.Year = 0 Then
            If Today.Month - dExpiryDate.Value.Month < 0 Then
                LBExpiryDate.Text = "THE ID IS OK"
                LBExpiryDate.BackColor = Color.Green
        
            Else
                If Today.Month - dExpiryDate.Value.Month = 0 Then
        
                    If Today.Day - dExpiryDate.Value.Day < 0 Then
                        LBExpiryDate.Text = "THE ID IS OK"
                        LBExpiryDate.BackColor = Color.Green
                    Else
                        LBExpiryDate.Text = "THE AGE IS EXPIRED "
                        LBExpiryDate.BackColor = Color.Red
                    End If
                    Else
                    LBExpiryDate.Text = "THE AGE IS EXPIRED "
                    LBExpiryDate.BackColor = Color.Red
        
                End If
            End If
        Else
            LBExpiryDate.Text = "THE AGE IS EXPIRED "
            LBExpiryDate.BackColor = Color.Red
        End If
        End If
        

        【讨论】:

        • 这有很多错误并且是不必要的复杂。例如,如果年份在到期年份之前,它将显示“已到期”。您可以直接比较 DateTime 对象,而不是将它们分解为日、月、年。
        猜你喜欢
        • 2021-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-03
        相关资源
        最近更新 更多