【问题标题】:VB.net Create Date Killswitch (Compare two Dates)VB.net 创建日期 Killswitch(比较两个日期)
【发布时间】:2018-12-28 14:37:08
【问题描述】:

我想在我的应用中实现基于日期的 killswitch,以便它在特定时间停止工作。因此,我确定了日期(例如 2019 年 2 月 1 日)。一旦系统的日期(我的应用程序在其中运行)大于 Killswitch 日期,我希望它停止工作。我试过了:

If Today.Date.toString() >= "02/01/2019" Then
End
Else
...

那没用。我遇到的问题是每台计算机上的日期格式不同,有的有 MM/dd/YYYY,有的有 dd/MM/YYYY,有的有 YYYY/月/日。是否仍然可以将所有日期转换为通用格式并进行比较?

【问题讨论】:

    标签: vb.net if-statement


    【解决方案1】:

    不要硬编码你的日期;那么格式就不是问题了。相反,请使用 DateTime 类的构造函数来创建具有特定年月日的击杀目标:

    Dim targetDT As New DateTime(2019, 2, 1)
    If DateTime.Today > targetDT Then
        ' ... do something in here ...
    End If
    

    【讨论】:

      【解决方案2】:

      如果所有日期都是标准格式,您可以使用 DateTime.Parse。此时,您将比较两个 DateTime 值,然后大于或等于将起作用。

      If DateTime.Now >= DateTime.Parse("02/01/2019") Then
          Environment.End
      End If
      

      为了手动解析日期,您需要知道它的格式,因为您需要从它的片段中创建 DateTime 对象。这是一个例子:

      Dim strDate As String = "12/28/2018"
      Dim year As Integer = Integer.Parse(strDate.Substring(6, 4))
      Dim month As Integer = Integer.Parse(strDate.Substring(0, 2))
      Dim day As Integer = Integer.Parse(strDate.Substring(3, 2))
      Dim d = New DateTime(year, month, day)
      

      【讨论】:

      • 注意,他们仍然需要知道它的格式。添加了一个解析指定格式之一的示例。
      【解决方案3】:

      你可以用这个

          Dim currentDate As DateTime = DateTime.Now
          If currentDate.Month >= 2 And currentDate.Day >= 1 And currentDate.Year >= 2019
                End
          End If
      

      【讨论】:

        【解决方案4】:

        另一种方法、cmets 和在线解释。

        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            If DateTime.Now > ExpireDate Then
                MessageBox.Show("Your trial period has expired")
                Close()
            End If
        End Sub
        
        Private ExpireDate As Date
        
        Private Sub OPCode3()
            'run once at first startup
            'Store As DateTime, then you can compare DateTime withour converserion or parsing
            ExpireDate = DateTime.Now.AddMonths(3)
        End Sub
        

        【讨论】:

          猜你喜欢
          • 2018-08-26
          • 2011-09-01
          • 2013-11-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多