首页 > 解决方案 > 如何只比较月份和年份?[VB]

问题描述

它非常简单,我只想使用月份和年份比较两个日期,如果输入日期(仅限月份和年份)高于或低于当前日期(月份和年份)。

问题是,当我比较两个字符串时

Dim dDate as DateTime

If Not (DateTime.TryParse(txtBox.Text, dDate)) Then
 MessageBox.Show("check date.")
Else
 txtBox.Text = dDate.ToString("MM/yyyy")
end If

IF dDate.ToString("MM/yyyy") < DateTime.Now.ToString("MM/yyyy")
 MessageBox.Show("Below") ' Problem: 03/2024 saying is below than 08/2019
Else
 MessageBox.Show("Above")
End If

有什么帮助吗?

更新

我将案例更改为

If (dDate.Month AndAlso dDate.Year) < (DateTime.Now.Month AndAlso DateTime.Now.Year) Then
 'input: 07/2019 
 'date expired
Else
'the problem is here
'saying 07/2019 is not < than 08/2019
End If

标签: vb.netwinforms

解决方案


我会避免使用字符串。

    Dim dDate As DateTime
    If Not (DateTime.TryParse(txtBox.Text, dDate)) Then
        'bad date
        MessageBox.Show("check date.")
    Else
        Select Case dDate.Year
            Case Is < DateTime.Now.Year
                MessageBox.Show("Below")
            Case Is > DateTime.Now.Year
                MessageBox.Show("Above")

            Case Else 'years are equal,check month
                Select Case dDate.Month
                    Case Is < DateTime.Now.Month
                        MessageBox.Show("Below")
                    Case Is > DateTime.Now.Month
                        MessageBox.Show("Above")
                    Case Else 'equal months
                        MessageBox.Show("SAME") '????
                End Select
        End Select
    End If

推荐阅读