2010-01-05 111 views
1

label1显示通过查询从数据库中获取的最后一个交易日期/时间。 label2是系统日期/时间。我有一个计时器执行一个命令按钮,之后我想检查label1中的日期/时间是否小于5分钟。如果是这样,那么我想要显示按摩。比较两个日期时间

但我不知道为什么我的代码无法执行此功能。 任何帮助将不胜感激。

Private Sub Command1_Click() 
    Dim date1 As Date 
    Dim date2 As Date 

    date1 = Format(Now, "yyyy/mm/dd hh:mm:ss") 
    date2 = Format(label1, "yyyy/mm/dd hh:mm:ss") 
    If DateDiff("n", date1, date2) < 2 Then 
     MsgBox ("Not Vending") 
    End If 
End Sub 

我也试过:

Private Sub Command1_Click() 
    Dim date1 As Date 
    Dim label1 As Date 

    date1 = Format(Now, "yyyy/mm/dd hh:mm:ss") 
    date2 = label1 
    If DateDiff("m", Now, date1) > DateDiff("m", Now, label1) Then 
     MsgBox ("Not Vending") 
    End If 
End Sub 

除了:

Private Sub Command1_Click() 
    If DateDiff("n", Now, label1) > 5 Then 
     MsgBox ("Not Vending") 
    End If 
End Sub 
+1

label1从哪里来?为什么你只能将日期类型转换为字符串才能在字符串上调用DateDiff(这会强制它将字符串转换回日期)?给我们多个版本的Command1_Click没有什么帮助,向我们展示一个最接近你认为应该工作的东西。 – AnthonyWJones 2010-01-05 10:31:15

回答

2

如果日期从DB比现在更早拉,则DateDiff总是会返回一个负数如果你通过Now作为第二个参数。看起来你正在检查时间的流逝,所以我会假设DB中的日期总是在Now之前。你需要切换到与其相比较现在和日期的顺序(DateDiff("n", date1, Now),而不是DateDiff("n", Now, date1)

Private Sub Command1_Click() 
    Dim date1 As Date 
    date1 = CDate(Label1.Caption) 
    If DateDiff("n", date1, Now) < 5 Then 
     MsgBox ("Not Vending") 
    End If 
End Sub 
+0

Raven的代码应该适合你。为了调试的目的,我会添加和其他语句,如Else MsgBox DateDiff(“n”,date1,Now)和“分钟差异” – jac 2010-01-05 23:01:48

+0

感谢您的回复得到它排序。 – user243732 2010-01-07 05:06:41

2

不使用DateDiff -function将直接计算与Date - 变量的另一种方式 - 因为引擎盖下,这些其实都是Doubles

Private Sub Command1_Click() 
    Dim date1 As Date 
    date1 = CDate(Label1.Caption) 
    '#12:05:00 AM# is representing a value of 5 Minutes in the Date-datatype 
    If (date1 - Now) < #12:05:00 AM# Then 
     MsgBox ("Not Vending") 
    End If 
End Sub 

如果您要检查的时间差,你也可以使用

Private Sub Command1_Click() 
    Dim date1 As Date 
    date1 = CDate(Label1.Caption) 
    '#12:05:00 AM# is representing a value of 5 Minutes in the Date-datatype 
    If Abs(date1 - Now) < #12:05:00 AM# Then 
     MsgBox ("Not Vending") 
    End If 
End Sub 

Abs(date1 - Now)返回的时间差为Date - 值

顺便说一句。 date1 = Format(Now, "yyyy/mm/dd hh:mm:ss")不会令人惊叹。由于Now返回Date - 值,Format转换是Date - 值成String并将其分配给date1转换是StringDate - 值使用日期格式的本地系统设置 - 这意味着,该方案将表现不同的不同系统。